Neamah Al-Naffakh
Neamah Al-Naffakh

Reputation: 163

sorting a matrix in MATLAB

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

Upvotes: 2

Views: 80

Answers (1)

Autonomous
Autonomous

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

Related Questions