How to vectorize this code?
显示 更早的评论
Could you let me know how to vectorize the below for-loop ?
pigrid = zeros(knum,epnum,sepnum,znum,sznum);
for ki = 1:knum
for epi = 1:epnum
for sepi = 1:sepnum
for zi = 1:znum
for szi = 1:sznum
pigrid(ki,epi,sepi,zi,szi) = epgrid(epi,sepi)*zgrid(zi,szi)*kgrid(ki)^alpha-f;
end
end
end
end
end
9 个评论
Adam Danz
2018-8-6
Please provide values of knum,epnum,sepnum,znum,sznum. If the current nested loop strategy works, why do you need to vectorize it? Assuming epgrid, zgrid, and kgrid and matricies, this should be really fast.
Here's what I got so far. It's a simplification but still relies on 3 of your 5 loops.
for ki = 1:knum
for epi = 1:epnum
for sepi = 1:sepnum
pigrid(ki,epi,sepi,:,:) = epgrid(epi,sepi)*zgrid(1:znum,1:sznum)*kgrid(ki)^alpha-f;
end
end
end
if zgrid(1:znum,1:sznum) == zgrid, then a further simplification would be
for ki = 1:knum
for epi = 1:epnum
for sepi = 1:sepnum
pigrid(ki,epi,sepi,:,:) = epgrid(epi,sepi)*zgrid*kgrid(ki)^alpha-f;
end
end
end
Further vectorization would require a few repmat() and reshape() function calls to store the results in your current 5D variable and I'm not sure you're going to save time by doing that. Nevertheless, I'd love to see a complete vectorization of this from someone who has more time to fiddle with it.
icdi
2018-8-6
OCDER
2018-8-6
Moved from Answers to here.
"Thanks for your response. znum is not 10 but 7. Sorry about my typo."
In that case, my other answer wouldn't have worked... hm... The only way I can see this loop go faster is to move the
kgrid(ki)^alpha
outside the nested loops to prevent recalculating this value many times.
OCDER
2018-8-6
By the way, just realized your ID name is "matwork" with a mathworks logo. Perhaps try changing your ID and logo so that it does not seem to impersonate MathWorks employees.
https://www.mathworks.com/matlabcentral/termsofuse.html Read Content 2.ii
icdi
2018-8-6
OCDER
2018-8-6
No problem. And make sure to accept @Adam's answer, once he copies it over to the Answer section :)
icdi
2018-8-6
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!