Vectorize double nested for loop with indexing using another matrix
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!