Matlab matrix operations without loops
Mostra commenti meno recenti
Hello. I have an issue with a code performing some matrix operations. It is getting to slow, because I am using loops. I am trying for some time to optimize this code and to re-write it with less or without loops. Until now unsuccessful. Can you please help me solve this:
pb = rand(10,15);
data = rand(10000,15);
[rP, cP] = size(pb);
[r, c] = size(data);
dist=zeros(r, rP);
C = zeros(r,1);
for h=1:r
min=inf;
for w=1:rP
dist(h,w)= sum((data(h,:) - pb(w,:)).^2);
if min > dist(h,w)
min= dist(h,w);
near_clust=w;
end
end
C(h) = near_clust ;
end
For large dimension the execution time of these two loops is very high. How can I optimize this?
Thank you,
Risposta accettata
Più risposte (1)
Guillaume
il 12 Set 2014
First of all, don't use min as the name of a variable as you can't then matlab's min function which you actually want.
Secondly, using matlab's min function you can calculate C in one go, outside both for loop:
[~, C] = min(dist, [], 2); %won't work if you have a variable called min
Finally, you can eliminate the inner loop entirely:
for h=1:r
dist(h, :) = sum(bsxfun(@minus, data(h,:), pb).^2, 2)';
end
[~, C] = min(dist, [], 2);
1 Commento
kusum bharti
il 12 Set 2014
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!