フィルターのクリア

distance between array entries

3 ビュー (過去 30 日間)
amateurintraining
amateurintraining 2017 年 11 月 29 日
コメント済み: Andrei Bobrov 2017 年 11 月 29 日
How do you write code to get which of the entries stored in an array it is closest to for each data point?
For example:
array: [4 9 7 3 10 19 2 11]
and you want to find which entry each entry is closest to. So, in the above array, the answer would be:
[4 5 2 1 2 8 4 5]
(the number 4 is closest in value to the 4th entry in the array...the number 9 is closest in value to the 5th entry in the array...etc.)
  1 件のコメント
Jos (10584)
Jos (10584) 2017 年 11 月 29 日
You should define " closest" more accurately! Why is 9 closer to 10 rather than 11? And I would argue that any number is closest to itself, so 1:8 would be my answer ;)

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

回答 (3 件)

KSSV
KSSV 2017 年 11 月 29 日
編集済み: KSSV 2017 年 11 月 29 日
Read about knnsearch.
A = [4 9 7 3 10 19 2 11] ;
B = [4 5 2 1 2 8 4 5] ;
idx = knnsearch(A',A','k',2) ;
iwant = idx(:,2)
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2017 年 11 月 29 日
+1

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


Andrei Bobrov
Andrei Bobrov 2017 年 11 月 29 日
a = [4 9 7 3 10 19 2 11];
[~,iout] = min(abs(a(:)-a(:)')+diag(nan(numel(a),1)),[],2);

Roger Stafford
Roger Stafford 2017 年 11 月 29 日
Let 'a' be your array (row vector.)
n = size(a,2);
[t,p] = sort(a);
q = 1:n; q(p) = q;
t = diff(t);
t = [inf,t;t,inf];
[~,r] = min(t);
r = (1:n)+2*r-3;
p = p(r(q)); % p is the desired result

カテゴリ

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