After a certain time for loop speed slow down?

8 views (last 30 days)
Alberto Paniate on 6 Oct 2020
Hi, I am creating a program with a for loop. As I have asked in another question I have learned to speed this process with vector and ok. But I would like to know why this thing happen.
Take this code:
A = zeros(1000,1000);
E0=10;
for k = 1:1000
k
for j = 1:1000
A(k,j)=E0*exp(-65*((k-500)^2+(j-500)^2)) *exp(-1i *6.5*((k-500)^2+(j-500)^2)); %gaussiana
end
end
On my computer the first 500 k are really fast, then after about 500, it is very slow, almost 0.8 sec for one k. Why?
Rik on 6 Oct 2020
Edited: Rik on 6 Oct 2020
Really strange, especially since the two values for the inner and outer loop don't seem to have an interchangeable effect.
I slightly modified your code and reproduced your finding on R2020b, R2015a, and R2011a (all Windows 10). The peaks for 1,1 and 501,501 are reproducible acros runs and releases (the latter is much more prominent on R2020b).
A = zeros(1000,1000);
E0=10;
k1_list=1:10:1000;
k2_list=1:10:1000;
t=NaN(size(A));
for k1 = k1_list
for k2 = k2_list
h_tic=tic;
for repeats=1:5%make a single line take enough time for tic,toc
A(k1,k2)=E0*exp(-65*((k1-500)^2+(k2-500)^2)) *exp(-1i *6.5*((k1-500)^2+(k2-500)^2));
end
t(k1,k2)=toc(h_tic);
end
end
[K1,K2]=ndgrid(k1_list,k2_list);
surf(K1,K2,t(k1_list,k2_list),'EdgeAlpha',0.3)
v=regexp(version,'(R[0-9ab]+)','tokens');v=v{1};title(v)
view(-20,40),xlabel('k1'),ylabel('k2'),colormap('jet'),set(gca,'ZLim',[0 3e-3]),caxis([-2e-3 2e-3])

You can create A without having two nested loops:
E0=10;
[km, jm] = meshgrid(1:1000, 1:1000);
A= E0*exp(-65*((km - 500).^2 + (jm - 500).^2)) .*exp(-1i *6.5*((km - 500).^2 + (jm - 500).^2));
Yes, you are right. This may be because of the internal storage of variables and accessing them. it has exp functions on imaginary variables that may have varying spped for differnt arguments

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!