Matlab matrix operations without loops
Show older comments
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,
Accepted Answer
More Answers (1)
Guillaume
on 12 Sep 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 Comment
kusum bharti
on 12 Sep 2014
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!