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 个)

类别

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