2
votes

I have a matrix that contains ( 6 rows, 2 columns) as shown in the attached image.

enter image description here

I'd like to have a new matrix (in MATLAB) that contains the second columns arranged in ascending order, but would like to keep their corresponding values in the row. for example: the output matrix looks like this

enter image description here

1

1 Answers

2
votes

You can do it as follows:

mat = randi(30, [6 2]);  % creating the matrix
[mat(:,2),ind] = sort(mat(:,2));
mat(:,1) = mat(ind,1);

If you have access to the sortrows function, it is simpler:

mat = sortrows(mat,2);