MATLAB: Is it taking so long to execute program

execution-timeMATLABspeed

Hello,
I have two similar programs, but their execution time is so different. This one executes very fast:
n(N_go)=ninf;
n(N_go-1)=ninf-epsi;
for m=(N_go-1):-1:2
n(m-1)=h^2/D*(B*n(m)^2-G)+2*n(m)-n(m+1);
end;
And this one takes very very long:
n(1)=n0;
n(2)=C/(2*D)*n(1)*h+n(1);
for m=2:1:N_go
n(m+1)=h^2/D*(B*n(m)^2-G)+2*n(m)-n(m-1);
end;
N_go=10000000 in both cases. Other parameters are also equal. Can someone explain to me, why second code is taking so long to execute?

Best Answer

What do you think MATAB must do when you do something like this:
tic
clear n
n(1) = 1;
for i = 1:10000000
n(i) = i;
end
toc
Elapsed time is 1.212347 seconds.
First, MATLAB declares the variable n as a scalar.
Then it replaces n with a vector of length 2, copying every element in n to a new location, since the variable need to be dynamically reallocated.
Then it repeats the process, over and over again, with bigger and bigger vectors each time.
How long do you think that will take?
What will happen if you change the code simply to:
tic
clear n
n = NaN(1, 10000000);
n(1) = 1;
for i = 1:10000000
n(i) = i;
end
toc
Elapsed time is 0.207284 seconds.
Why is the second code different? I preallocated the vector n. One line was added. But having allocated space for the ENTIRE vector, now the vector need not be dynamically resized, reallocated with each element added. The vector now never changes size.
What did you do in your first example, that ran quickly? What was the VERY first line?
n(N_go)=ninf;?
What does that do? THINK!
clear n
N_go = 10;
n(N_go) = inf;
n
n =
0 0 0 0 0 0 0 0 0 Inf
So a vector is created with all zero elements. It was preallocated, by setting the LAST element to some value.
In the second code that you wrote, where did you start? What was the size of n at the beginning?
clear n
n(1) = 0;
whos n
Name Size Bytes Class Attributes
n 1x1 8 double
n was a scalar when you started that loop.
Related Question