How to sort the matrix rows based on a function over the rows

Let's say I have a Nx3 matrix M of double.
Consider, for example, a function Map(a,b,c) that returns a double
How can I sort M so that the rows with smallest Map come first?
For example, the first row should be i if Map(M(i,1), M(i,2), M(i,3)) value is the smallest between Map(M(j,1), M(j,2), M(j,3)) for any 1 ≤ j ≤ N and j ≠ i

Risposte (2)

I have no clue what a,b and c are but I assume the function Map(a,b,c) will return a vector of N elements:
X = Map(a,b,c)
[sortX, idx] = sort(X) % sort X, retrieve the sorting indices
sortedM = M(idx,:) % sort M accordingly

6 Commenti

Daniel Tex
Daniel Tex il 13 Dic 2017
Modificato: Daniel Tex il 13 Dic 2017
the values for a,b,c should be the the 3 elements of each row of M (and M is a double matrix)
sorry I didn't mention, thought it was implicit
I want row i to be the first if Map(M(i,1), M(i,2), M(i,3)) value is the minimum between Map of all other rows, and so on
Does Map allow vectors?
X = Map(M(:,1),M(:,2),M(:,3))
if not:
X = arrayfun(@(r) Map(M(r,1),M(r,2), M(r,3)), 1:size(M,1))
I tested and X was not M after sorting... let me give you an example
M1 = |1 2 3|
|4 5 6|
|7 8 9|
Map(a,b,c){
if(a == 1 && b == 2 && c == 3) return 2
if(a == 4 && b == 5 && c == 6) return 3
if(a == 7 && b == 8 && c == 9) return 1
}
so after the sorting, the matrix I'm looking for is:
M2 = |7 8 9|
|1 2 3|
|4 5 6|
because Map(7,8,9) is the smallest value, followed by Map(1,2,3) and Map(4,5,6)
Did you try to run the arrayfun line on your matrix M as above? What does it return?
Retrieving the indices of a sort and use it to re-order another array is a classic trick ...
yes I did. Firstly I changed Map to receive an array as argument, then I did:
X = arrayfun(@(r) Map(M(r,:)), 1:size(M,1))
X is the array with the outputs for Map of each row from 1 to N
so, then it should work ... or am I missing something?

Accedi per commentare.

[~ii] = = sort(arrayfun(@(r) Map(M(r,:)), 1:size(M,1)));
out = M(ii,:);

Categorie

Richiesto:

il 13 Dic 2017

Risposto:

il 14 Dic 2017

Community Treasure Hunt

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

Start Hunting!

Translated by