How to vectorize this code?

1 次查看(过去 30 天)
icdi
icdi 2018-8-6
评论: icdi 2018-8-6
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 个评论
OCDER
OCDER 2018-8-6
No problem. And make sure to accept @Adam's answer, once he copies it over to the Answer section :)
icdi
icdi 2018-8-6
Yes yes. Thanks again for your advice!

请先登录,再进行评论。

采纳的回答

Adam Danz
Adam Danz 2018-8-6
Creating a fully vectorized version of these nested loops seems either not possible or not practical. Here's a summary of some improvements listed in the comment section under the question.
This simplification 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
@OCDER also recommended moving kgrid(ki)^alpha outside of the loop which would eliminate ~10000 exponential calculations.
Assuming kgrid(1:knum)==kgrid,
kgalpha = kgrid.^alpha; % or kgrid(1:knum).^alpha
for ki = 1:knum
for epi = 1:epnum
for sepi = 1:sepnum
pigrid(ki,epi,sepi,:,:) = epgrid(epi,sepi)*zgrid*kgalpha(ki)-f;
end
end
end
Lastly, you could remove the " -f" to after the loop like this:
kgalpha = kgrid.^alpha; %or kgrid(1:knum).^alpha
for ki = 1:knum
for epi = 1:epnum
for sepi = 1:sepnum
pigrid(ki,epi,sepi,:,:) = epgrid(epi,sepi)*zgrid*kgalpha(ki);
end
end
end
pigrid = pigrid - f;
  2 个评论
Adam Danz
Adam Danz 2018-8-6
编辑:Adam Danz 2018-8-6
All of these versions have been tested with fake data where epgrid, zgrid, and kgrid were matrices with random numbers and the loop variables used the values you shared above. Additionally, you should test your current nested loop code with the simplified version you choose to ensure you've got the same values. To do that, you could use
isequal(pigrid, pigrid2).
icdi
icdi 2018-8-6
Oh Thanks! I learned a lot from your comments. Also thanks for letting me know the way to compare the versions.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by