Need help removing this for loop

5 ビュー (過去 30 日間)
xtremecheez
xtremecheez 2017 年 11 月 14 日
コメント済み: Andrei Bobrov 2017 年 11 月 14 日
This is the last step in vectorizing my code, but I just can't see how to get rid of the pesky for loop. Any assistance is appreciated.
I've replaced the variables with numbers for a more readable example.
%size(Cp) = [5,3,100]
%size(Tr) = [2e4,100]
A = zeros(5,2e4,100);
for ii = 1:100
A(:,:,ii) = Cp(:,Tr(:,ii),ii);
end
  1 件のコメント
Stephen23
Stephen23 2017 年 11 月 14 日
編集済み: Stephen23 2017 年 11 月 14 日
"I just can't see how to get rid of the pesky for loop. Any assistance is appreciated."
Don't get rid of the loop. Using a loop is probably the neatest, clearest, and most efficient way to solve that task. Anything else will just pointlessly obfuscate your code and waste your time later when you forget what it does.

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

採用された回答

Walter Roberson
Walter Roberson 2017 年 11 月 14 日
If I got my calculations right, then:
A = Cp( bsxfun(@plus, (1:size(Cp,1)).', bsxfun(@plus, (Tr - 1) * size(Cp,1), ((1:size(Cp,3)-1) * size(Cp,1) * size(Cp,2)) ) );
This is difficult to read and difficult to write. I cannot recommend it unless perhaps run time is very important -- and even then considering the size of the internal matrices involved and the number of operations used to construct them, I would tend to doubt that it is more efficient.
Your existing code with a loop is easier to read and probably nearly as efficient, possibly more efficient.
This is one of those cases where the goal to "vectorize" requires constructing large intermediate arrays and use calculations that have no obvious meaning. Since typically more time is spent programming and debugging and documenting than is spent in execution of a program, it is unlikely that you would be gain anything meaningful by vectorization.
  2 件のコメント
Jan
Jan 2017 年 11 月 14 日
+1: The large intermediate index array is not efficient.
Walter Roberson
Walter Roberson 2017 年 11 月 14 日
I think I forgot a permute() around the second bsxfun()

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 11 月 14 日
編集済み: Andrei Bobrov 2017 年 11 月 14 日
[k,m,n] = size(Cp);
A = Cp((1:k)' + k*(permute(Tr,[3 1 2]) - 1)+reshape(0:n-1,1,1,[])*k*m);
  3 件のコメント
Walter Roberson
Walter Roberson 2017 年 11 月 14 日
It looks to me as if Andrei's code is for R2016b and later.
Andrei Bobrov
Andrei Bobrov 2017 年 11 月 14 日
Yes.

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

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by