Is there a faster way to run my code?

1 回表示 (過去 30 日間)
Gn Gnk
Gn Gnk 2020 年 9 月 23 日
コメント済み: Gn Gnk 2020 年 9 月 29 日
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)
distance(count2,:)=abs(r(count1,:)-C(count2,:));
dist(count2)=sum(distance(count2,:),2);
end
[dist_hard index_hard(count1)]=min(dist);
end
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 .

採用された回答

Walter Roberson
Walter Roberson 2020 年 9 月 23 日
[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".
  11 件のコメント
Walter Roberson
Walter Roberson 2020 年 9 月 27 日
Does C consist of only values 0 and 1? If so then the distance from r(count1,:) to C(count2,:) is
nnz(r(count1,:) ~= C(count2,:))
and you could vectorize over all C entries as
sum(r(count1,:) ~= C,2)
providing you are using R2016b or later.
If C does consist entirely of 0 and 1, then you can do your entire calculation as
[dist_hard, index_hard] = max(r*C.',[],2);
Note that in the case of ties in the distance, this code will pick the first of them.
Gn Gnk
Gn Gnk 2020 年 9 月 29 日
Thank you so much for your effort !

サインインしてコメントする。

その他の回答 (2 件)

Bruno Luong
Bruno Luong 2020 年 9 月 23 日
編集済み: Bruno Luong 2020 年 9 月 23 日
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 2020 年 9 月 27 日
編集済み: Bruno Luong 2020 年 9 月 27 日
For binary arrays
r=rand(50,8)>0.5;
C=rand(60,8)>0.5;
[dmin, index_hard] = min(sum(xor(r,permute(C,[3 2 1])),2),[],3);
index_hard'

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by