Given a vector, how to pair them by nearest?

Hi,
I have a vector with values. I have to pair them by nearest.
Is there any magic command to do it?
Thanks!

 採用された回答

Sean de Wolski
Sean de Wolski 2013 年 2 月 25 日
編集済み: Sean de Wolski 2013 年 2 月 25 日

0 投票

doc knnsearch
If you have the Statistics Toolbox this sounds like your magic command.
Of course, if you just need a magic command, you can always run:
magic(5)
More Using knnsearch here is probably overkill when you could just use a for-loop, finding the minimum of the exclusive set. But here is how I would do this with knnsearch:
[idx,D] = knnsearch(values',values','K',2) %Get two because the first will be the value itself
idx(:,2) %2nd column is the closest one that isn't the same
D(:,2) %Distance
values(idx(:,2)) %What was the original value?

7 件のコメント

Sean de Wolski
Sean de Wolski 2013 年 2 月 25 日
You could also use pdist which might be faster.
Dani Tormo
Dani Tormo 2013 年 2 月 25 日
I found knnsearch before but I cannot figure out how to use it for my purpose, X and Y have to be arrays.
My vector could be this one:
values = [1.5 0.6 1.9 0.4 1.3 0.1];
How to pair them using knnsearch or pdist?
Sean de Wolski
Sean de Wolski 2013 年 2 月 25 日
So you have values, and you want to know the closest element from each in it? So 0.1 would pair with 0.4 which would pair with 0.6?
Sean de Wolski
Sean de Wolski 2013 年 2 月 25 日
See More
Dani Tormo
Dani Tormo 2013 年 2 月 25 日
No because when two are paired it excludes from pairing with others. And the sum of all differences will have to be the minimum.
For example, if we pair this way:
  • 0.6 and 0.4
  • 1.5 and 1.3
  • 1.9 and 0.1
and summing the total differences, it gives us 2.2.
But if we pair them like this:
  • 0.1 and 0.4
  • 1.9 and 1.5
  • 0.6 and 1.3
it gives a total difference of 1.4. This result will be better than the previous one.
Teja Muppirala
Teja Muppirala 2013 年 2 月 25 日
Assuming an even number of elements, isn't the answer just SORTing the vector and taking two at a time?
values = [1.5 0.6 1.9 0.4 1.3 0.1];
reshape(sort(values),2,[])'
Dani Tormo
Dani Tormo 2013 年 2 月 26 日
Yes man, you're right.
I wrote a program to evaluate random values, I run it for several minutes and sorting them and grouping always gives the minimum value.
Thanks for your help and time!

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2013 年 2 月 25 日

0 投票

What do you mean by ' pair them by nearest '? Do you want to SORT the values?
Otherwise, can you give a small example of your vector and the required result of such a magic function?

1 件のコメント

Dani Tormo
Dani Tormo 2013 年 2 月 25 日
編集済み: Dani Tormo 2013 年 2 月 25 日
I answered your question on the Sean's answer.

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

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by