1
votes

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
2
Indexing in Matlab starts at 1, your index vectors will return an error in their current format.Cape Code

2 Answers

2
votes

How about:

ModifiedA=A(RowVector,ColumnVector);

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

1
votes

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);