sorting matrix in matlab based on another vector

2019-06-05 21:54发布

问题:

I have a 2D matrix and want to sort rows and columns based on two other vectors i.e. one for ordering rows another for ordering columns in MATLAB

Example: A (Matrix to order)

0 1 2 3 4
1 1 8 9 7
2 3 4 6 2
3 1 2 0 8

Row Vector (Order for sorting rows of matrix A)

1
4
2
3

And column vector

1 5 4 2 3

Modified A

0   4   3   1   2
3   8   0   1   2
1   7   9   1   8
2   2   6   3   4

回答1:

How about:

ModifiedA=A(RowVector,ColumnVector);

Note: Matab's indexing starts at 1 not at 0, adapt your indexing vectors accordingly.



回答2:

In MATLAB, you can use the second output of sort to get the 1-based indexes that MATLAB is looking for (in this case you could have just added 1, but using sort works even if the row and column vectors are not consecutive).

[~,rowIdx] = sort(rowVector);
[~,colIdx] = sort(colVector);

And then you can apply the indexing operation to the matrix:

modifiedA = A(rowIdx, colIdx);