notice I'm poor in English. but I take another example to, can be explain answer.
consider
'A', a 512*512 matrix.
for example:
A=imread('lena.tif');
and we like to calculate differences between each two pixels.
the program Can be written as follows
****************************** (1)
clear A B
A=imread('s\lena.tif');
tic
for i=1:512
for j=1:511
B(i,j)=A(i,j+1)-A(i,j);
end
end
toc
****************************** (2)
clear A B
A=imread('s\lena.tif');
tic
B(512,511)=0;
for i=1:512
for j=1:511
B(i,j)=A(i,j+1)-A(i,j);
end
end
toc
****************************** (3)
clear A B
A=imread('s\lena.tif');
tic
B=A
,2:512)-A
,1:511);
toc
****************************** (4)
clear A B
A=imread('s\lena.tif');
tic
B(512,511)=0;
B=A
,2:512)-A
,1:511);
toc
****************************** (5)
clear A B
A=imread('s\lena.tif');
tic
B(512,511)=0;
B
,
=A
,2:512)-A
,1:511);
toc
***********************************************************
***********************************************************
results (amount time, program need)
(1) Elapsed time is 0.072111 seconds.
(2) Elapsed time is 0.011675 seconds.
(3) Elapsed time is 0.001771 seconds.
(4) Elapsed time is 0.002383 seconds.
(5) Elapsed time is 0.005198 seconds.
Experiment Result
(2) is faster (1), because we consider the size of B at the first.
(3) is fastest, because we don't use 'for' loop.
(4) & (5) is not better, because we don't need to consider size of B.
but why, we get this results.
at the (1), when 'i' & 'j' increment, size of 'B is increment too. and MATLAB should find the new memory for 'B' and assign it too 'B', and then change 'B'. communicate to memory, is very slower.
at the (3), is faster, because the 'for' loop in "MATLAB" is slower than "C" , "FORTRAN".
at the (4), the "B(512,511)=0;" statement isn't useful. because at the "B=A
,2:512)-A
,1:511);" statement, MATLAB clear "B" and then create "B" and assign result.
and at the (5), MATLAB one time, need to create "B" and set all memory of it to zero. and then need to change all elements of "B", to can assign the result.