Sorting element pairs by differences?
Show older comments
Suppose values is a vector, how to produce a matrix whose rows contain pairs of elements of this vector, ordered ascending by the differences between the elements.
For example:
values = [1,2,1.5,1.9]
I want the matrix
differences = [1.9 2; 1.5 1.9; 1 1.5; 1.5 2; 1 1.9; 1 2]
Accepted Answer
More Answers (2)
Massimo Zanetti
on 7 Oct 2016
3 votes
More elegant is to use pdist, that does the bad job..
Jos (10584)
on 7 Oct 2016
1 vote
Take a look at NCHOOSEK, ABS, DIFF, and SORT:
- with X = nchoosek(values,2) you can get all the 6 different combinations
- use Y = abs(diff(X)) to get the absolute differences
- the second output of the function sort, applied tot these latter values, can be uses to sort the combinations accordingly.
Categories
Find more on Shifting and Sorting Matrices 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!