Need help removing this for loop
古いコメントを表示
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 件のコメント
"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.
採用された回答
その他の回答 (1 件)
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 件のコメント
Andrei Bobrov
2017 年 11 月 14 日
For this solution there is no practical application - this is just gymnastics for the mind. (Please see Walter's answer and Stephen's comment).
Walter Roberson
2017 年 11 月 14 日
It looks to me as if Andrei's code is for R2016b and later.
Andrei Bobrov
2017 年 11 月 14 日
Yes.
カテゴリ
ヘルプ センター および 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!