Is there a faster way to run my code?

1 view (last 30 days)
Hello ,
i wrote the code bellow . Is there any faster and more efficient way to run this code (not using for-loop for example or something like that):
for count1=1:length(r)
for count2=1:length(C)
[dist_hard index_hard(count1)]=min(dist);
The problem here is that when r or C contain many elements the code is slow and i its more than obvious that i dont want that .
Any help would be valuable .

Accepted Answer

Walter Roberson
Walter Roberson on 23 Sep 2020
[dist_hard, index_hard] = min( pdist2(r, distance, 'cityblock'), [], 2);
Note: the distance measure you are using is the L1-norm, also known as "city block".
Gn Gnk
Gn Gnk on 29 Sep 2020
Thank you so much for your effort !

Sign in to comment.

More Answers (2)

Bruno Luong
Bruno Luong on 23 Sep 2020
Edited: Bruno Luong on 23 Sep 2020
Use knnsearch if you have the right toolbox (I don't so the code is untested)
[index_hard, dist_hard] = knnsearch(C,r,'K',1,'Distance','cityblock')

Bruno Luong
Bruno Luong on 27 Sep 2020
Edited: Bruno Luong on 27 Sep 2020
For binary arrays
[dmin, index_hard] = min(sum(xor(r,permute(C,[3 2 1])),2),[],3);


Find more on Entering Commands 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!