How to code a faster loop
Mostrar comentarios más antiguos
I have a program that running loop, i=1:n, where n in the magnitude of 10'000. I found out that this part of the loop could be the main cause of slowing down the program significantly. Before adding this part overall I only need on average less than 3min. Now, I need 3.5hrs.
Part of the formulation basically requires us to deduct current value (i), with the value before (i-1). While running, I see repeatiton of e.g s(i) = columns 5 through 10 all the way to 1000 (n value). Same goes to ds(i). Not sure if this is avoidable and seems to be the root of the long computation time.
clc, clear all
ntrial=1000;
for ntl = 1:ntrial
int=0.8
ds1=0
ds2=0.2
n=1000.
x(1) = 0;
y(1) = 0;
xt(1)=2;
yt(1)=3;
un=0;
en=0;
ms=0;
% s(1)=0
SDEG=90;
for i=1:n;
dist(i) = sqrt(((x(i)-xt(i))^2)+((y(i)-yt(i))^2));
% dist(i) = 5+x(i)+y(i);
%******* get angle between 2 points *****
angleDEG=atand((yt(i)-y(i))/(xt(i)-x(i)))
angleRAD=angleDEG/180*pi
%******* get s value *************************************************
if angleDEG<=SDEG
s(i)=(900/dist(i))*exp(-2*(angleRAD)^2)+int
un=un+1
else
s(i)=int
en=en+1
end
if (i==1) % When i=1, i-1 = 0 dont exist.we use this to defined the initial condition
% s(i-1)=s(i)
ds(1)=0
s1=ds1+s(i)
s2=ds2+s(i)
else
ds(i)= s(i)-s(i-1) % Now i>1, we can procedd with the usual formulation
s1=ds1+s(i-1) % As ds= s(now)-s(previous)
s2=ds2+s(i-1)
end
x(i+1)=x(i);
y(i+1)=y(i);
xt(i+1)=xt(i);
yt(i+1)=yt(i);
if ds(i)>=0.2;
ms=1;
end
end
data(ntl,:)=[ms un en];
end
toc
Thank you for the help.
Respuesta aceptada
Más respuestas (1)
Julian Tan
el 10 de Ag. de 2021
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
