nested for loop take ages to run, any suggestions ?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
Walter Roberson
2019-5-18
编辑:Walter Roberson
2019-5-18
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.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!