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 件)
Jos (10584)
2017 年 12 月 13 日
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 件のコメント
Daniel Tex
2017 年 12 月 13 日
編集済み: Daniel Tex
2017 年 12 月 13 日
Jos (10584)
2017 年 12 月 13 日
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))
Daniel Tex
2017 年 12 月 13 日
編集済み: Daniel Tex
2017 年 12 月 13 日
Jos (10584)
2017 年 12 月 13 日
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 ...
Daniel Tex
2017 年 12 月 13 日
編集済み: Daniel Tex
2017 年 12 月 13 日
Jos (10584)
2017 年 12 月 14 日
so, then it should work ... or am I missing something?
Andrei Bobrov
2017 年 12 月 14 日
[~ii] = = sort(arrayfun(@(r) Map(M(r,:)), 1:size(M,1)));
out = M(ii,:);
カテゴリ
ヘルプ センター および 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!