How can i remove for loops?

1 回表示 (過去 30 日間)
Matteo
Matteo 2014 年 1 月 10 日
コメント済み: Matteo 2014 年 1 月 13 日
I'm trying to remove for loops from a code I wrote long time ago.
function [Rup] = updateR(A,E,S)
[imax,jmax,zmax] = size(A);
for z = 1 : zmax
Stmp = S(:,:,setdiff(1:zmax,z));
Atmp = A(:,:,setdiff(1:zmax,z));
Etmp = E(:,:,:,:,setdiff(1:zmax,z));
for i = 1 : imax
for j = 1 : jmax
sumtmp = permute(sum(sum(Etmp(i,j,:,:,:), 3), 4),[1 2 5 3 4]);
beta = (Stmp(i,j,:)+Atmp(i,j,:)+sumtmp);
n = - max(beta);
EEtmp = E(i,j,:,:,z);
Rup (i,j,z) = S(i,j,z) + n + sum(EEtmp(:));
end
end
end
A,R,S are [N x M x P] matrices.
I tried a lot by myself, but I have no confidence with the tricks useful to remove loops. Can anyone help me?
Matteo

採用された回答

Sean de Wolski
Sean de Wolski 2014 年 1 月 10 日
Just preallocating Rup should speed this up:
First line:
Rup = zeros(size(A));

その他の回答 (1 件)

Matteo
Matteo 2014 年 1 月 10 日
Thanks! how much will it affect the speed?
I'm also interested to learn something new about the for loops removal.
  2 件のコメント
Sean de Wolski
Sean de Wolski 2014 年 1 月 10 日
Unless this is going into production or being run millions of times, the time it would take to "vectorize" this will take longer than the running time of the code. Preallocating will speed it up most of the way.
As for how much you will see for a speedup? Try it!
Matteo
Matteo 2014 年 1 月 13 日
I tried and the execution time was reduced by 20%, thank you!
Anyway i need to speed it up more, have you other advices?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by