nested for loop take ages to run, any suggestions ?

2 Ansichten (letzte 30 Tage)
Moha al
Moha al am 18 Mai 2019
Kommentiert: Moha al am 21 Mai 2019
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
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.
Moha al
Moha al am 21 Mai 2019
how can I create a 3D matrix as for each xi,yj I get an array for time ?
like i take t and expand it to be 3D matrix so I get rid of the for loop and maybe use parallel computation to run it faster.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Produkte


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by