Speed up nested for loop
2 views (last 30 days)
Show older comments
Hi,
I am looking for ways to speed up the nested for loop below, but am having trouble working out how- I have tried to vectorise with meshgrid but this didn't seem to work greatly.
for ix=2:nx-1
for jy=2:ny-1
phinew(ix,jy)=0.5*1/((dx^2)+(dy^2))*((dy^2)*(phiold(ix+1,jy)+phiold(ix-1,jy))+(dx^2)*(phiold(ix,jy+1)+phiold(ix,jy-1)));
end
end
nx and ny are both = 100, and phinew and phiold are 100x100 doubles. Dy and Dx are related to lengths input by the user.
1 Comment
dpb
on 6 Dec 2019
But dx, dy are independent of ix,jy. Compute the constants outside the loop; not sure if the ML JIT compiler is smart enough to find the invariant common expressions or not. Don't rely on it; give it some help.
Look at filter2
Reverse order of the loops and iterate down column first...altho 100x100 is small enough to not make cache miss likely.
Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!