Reputation: 163
I have a matrix that contains ( 6 rows, 2 columns) as shown in the attached image.
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
Upvotes: 2
Views: 80
Reputation: 9075
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);
Upvotes: 2