After a certain time for loop speed slow down?

5 vues (au cours des 30 derniers jours)
Alberto Paniate
Alberto Paniate le 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?
  2 commentaires
Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam le 6 Oct 2020
How much RAM do you have? Matlab may write the variables on hard disk when memory is low
Rik
Rik le 6 Oct 2020
Modifié(e) : Rik le 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
figure(1),clf(1),set(gcf,'menu','none','toolbar','none')
[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])

Connectez-vous pour commenter.

Réponses (1)

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam le 6 Oct 2020
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));
  2 commentaires
Rik
Rik le 6 Oct 2020
As Alberto mentioned in his question, he does know how to vectorize this, but the slowdown is not explained.
Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam le 6 Oct 2020
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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by