Vectorize double nested for loop with indexing using another matrix

조회 수: 2 (최근 30일)
Doanh Luong
Doanh Luong 2019년 2월 26일
편집: Doanh Luong 2019년 2월 26일
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개)

카테고리

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