# Implement iterations on MATLAB

1. Jan 24, 2012

### sandy.bridge

Hello all,
I am trying to play around with MATLAB so I can become familiar with it. I have absolutely no programming experience, si it's a bit confusing for me. I have this formula:
$$v(t)=10(1-e^{-t})$$
and I want to implement iterations on MATLAB for 0<=t<=5.

I understand that I need to start "for loop", but I'm not entirely sure how to go about it. I know to start it,
"for i=0:n"

Any suggestions and explanations?

Last edited by a moderator: Jan 25, 2012
2. Jan 24, 2012

### Number Nine

Re: Matlab

Do you mean that you want to apply that function to each value of t from 1 to 5? There's no need to use a for loop.

t = 1:5;
v = 10*(1 - e.^(-t))

3. Jan 24, 2012

### jhae2.718

Re: Matlab

Try this:
Code (Text):

t = linspace(0, 5, 1000); [COLOR="SeaGreen"]% Produces 1000 data points linearly spaced on [0,5].[/COLOR]
v = 10*(1 - exp(-t));

v will then be in your workspace and you can do anything with it. For plotting, the more points you use the better the plot will be.

In MATLAB, you should always prefer using vectors to for loops, e.g. use this:
Code (Text):

x = 0:.01:100;
y = x .^ 2;

Code (Text):

x = 0:.01:100;
[COLOR="Blue"]for[/COLOR] i = 1:length(x);
y(i) = x(i) .^ 2;
[COLOR="Blue"]end[/COLOR]

Here is a quick program that tests the speed of a for loop versus a vector operation:
Code (Text):

t = cputime;
e = tic;
x = 0:.01:1000000;
[COLOR="Blue"]for[/COLOR] i = 1:length(x);
y(i) = x(i) .^ 2;
[COLOR="Blue"]end[/COLOR]
fprintf([COLOR="DarkOrchid"]'for: cputime: %f elapsed: %f \n'[/COLOR], [cputime - t, toc(e)]);
t = cputime;
e = tic;
x = 0:.01:1000000;
y = x .^ 2;
fprintf([COLOR="DarkOrchid"]'vec: cputime: %f elapsed: %f \n'[/COLOR], [cputime - t, toc(e)]);

On my computer it outputs:
Code (Text):

for: cputime: 12.850000 elapsed: 12.723039
vec: cputime: 1.270000 elapsed: 1.395663

As you can see, even with the small example, MATLAB is more efficient using vectors than loops.

Last edited: Jan 24, 2012
4. Jan 25, 2012

### sandy.bridge

Re: Matlab

Can you guys recommend a good book for beginners? I was also attempting to implement Euler's method for differentials.

5. Jan 27, 2012