sort a matrix for the size of the first column in matlab

You can sort a matrix by the size of its first column in MATLAB with the sortrows function. Here is an example:

main.m
A = [5 2 3; 1 4 2; 9 7 1; 2 3 6];
sortedA = sortrows(A, 1);
60 chars
3 lines

This will sort the matrix A by the first column, so the output will be:

main.m
1     4     2
2     3     6
5     2     3
9     7     1
56 chars
5 lines

In this example, the first column is [5; 1; 9; 2], so the matrix is sorted based on these values.

Note that if you want to sort by the size (number of elements) of the first column instead of its values, you can use the size function to get the size of the first column, and then sort based on that. Here's an example:

main.m
A = [5 2 3; 1 4 2; 9 7 1; 2 3 6];
[~, idx] = sort(size(A(:, 1)));
sortedA = A(idx, :);
87 chars
4 lines

This will sort the matrix A by the size of its first column, so the output will be:

main.m
9     7     1
5     2     3
1     4     2
2     3     6
56 chars
5 lines

In this example, the first column has size 4, so the last row comes first, followed by the first row which has size 3, etc.

related categories

gistlibby LogSnag