필터 지우기
필터 지우기

Sorting element pairs by differences?

조회 수: 1 (최근 30일)
Marco Bakker
Marco Bakker 2016년 10월 7일
댓글: Jos (10584) 2016년 10월 7일
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]

채택된 답변

uu tsi
uu tsi 2016년 10월 7일
the following is my code
values = [1,2,1.5,1.9];
ss = nchoosek(values, 2);
[~, idx] = sort(abs(diff(ss')));
res = ss(idx, :)
  댓글 수: 1
Jos (10584)
Jos (10584) 2016년 10월 7일
Thanks for having put my answer in code. As a follow-up: diff(A,1,2) is faster than diff(A'), and A.' (transpose)is more versatile than A' (conjugate transpose).

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Massimo Zanetti
Massimo Zanetti 2016년 10월 7일
More elegant is to use pdist, that does the bad job..

Jos (10584)
Jos (10584) 2016년 10월 7일
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.

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by