user26782
user26782

Reputation: 3

How to sort specific set of rows with specific column?

In Matlab, I would like to sort first 3 rows of a matrix A with column 2 and then next 3 rows without changing the first three rows again with column 2. e.g. for the matrix is below

A = [1 6 50;
     5 2 50;
     7 1 50;
     2 5 53;
     5 1 53;
     7 3 53]

I want to get

B = [7 1 50;
     5 2 50;
     1 6 50;
     5 1 53;
     7 3 53;
     2 5 53;]

Later, with the same logic, I would like to sort a matrix with 100 rows.

Upvotes: 0

Views: 67

Answers (1)

Tobias Ribizel
Tobias Ribizel

Reputation: 5421

You can do this by combining the sortrows method with the submatrix operation:

A(1:3,:) = sortrows(A(1:3,:), 2)
A(4:6,:) = sortrows(A(4:6,:), 2)
...

If your matrix is larger, you can do it with a simple for loop:

for i = 1:3:100
    A(i:i+2,:) = sortrows(A(i:i+2,:), 2)
end

Upvotes: 2

Related Questions