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

回答(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 个评论

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?

请先登录,再进行评论。

类别

帮助中心File 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