nested for loop take ages to run, any suggestions ?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have a code which contains 3 for loops as follows
dt=0.01
for x=1:15
for y-2000:2000
t=sqrt(x^2+y^2)/1000
for i=1:100000 % calaculate over period of time
a= x*(y+c/t)
b= cos(x/pi)
c=@function(x,y)
a,b and c are arbitrary but i meant that i have some variables which are calculated using x,y and t
q(x,y,t)=scalar
s(x,y,t)=scalar
end
store x values in a vector
store y values in a vector
store q values in a vector
store s values in a vector
t=t+dt;
end
end
this code would take weeks to run and I haven't been able to find a way to run it faster.
the third loop is the one taking time.
I dont't know if parallel computing could help or not?
any suggestions or advice ?
6 Kommentare
Walter Roberson
am 18 Mai 2019
Bearbeitet: Walter Roberson
am 18 Mai 2019
You are evolving in time. Unless there are analytic solutions that can directly give you the value at any particular time without doing the previous steps, then you need to have gone through the previous steps. You probably cannot eliminate the time loop.
In some cases, the contribution at a particular time can be calculated without knowing what has happened in the past, but the net value at a time is the sum of the previous contributions. In cases like that you can sometimes calculate the contributions individually in vectorized form and then cumsum() them along the time dimension.
Depending on exactly what functions you are using, what you might be able to do is eliminate the first and second loop, leaving only the time loop, using vectorized operations to calculate for all of the x, y locations simultaneously.
Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!