Sorting element pairs by differences?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Marco Bakker
el 7 de Oct. de 2016
Comentada: Jos (10584)
el 7 de Oct. de 2016
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]
0 comentarios
Respuesta aceptada
uu tsi
el 7 de Oct. de 2016
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 comentario
Jos (10584)
el 7 de Oct. de 2016
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).
Más respuestas (2)
Massimo Zanetti
el 7 de Oct. de 2016
More elegant is to use pdist, that does the bad job..
0 comentarios
Jos (10584)
el 7 de Oct. de 2016
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.
0 comentarios
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!