Vectorize double nested for loop with indexing using another matrix
2 ビュー (過去 30 日間)
古いコメントを表示
I tried to vectorize the following code:
n = 25; m = 5;
B = rand(n,n);
C = randsample(1:n,m);
Auc = zeros(1,m);
Au = zeros(1,n);
tic
for i = 1:10000
for u = 1:n
for c = 1:m
Auc(c) = B(u,C(c));
end
Au(u) = max(Auc);
end
A = sum(Au);
end
t1 = toc;
The vectorize version of the code is as follows:
D = zeros(n,m);
Au2 = zeros(1,m);
tic
for i = 1:10000
D = B(1:n,C(1:m));
Au2 = max(D,[],2)';
A2 = sum(Au2);
end
t2 = toc;
However, everytime I run t2 is bigger than t1. For example, t1 = 0.0086 and t2 = 0.0139.
Is there any problem with the vectorize version? Thank you very much for your help!!
0 件のコメント
回答 (0 件)
参考
カテゴリ
Help Center および 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!