Buntalan
Buntalan

Reputation: 183

matlab sort one column and keep respective values on second column

How do I just do a simple sort in matlab. I always have to use the excel link to import my data, sort it, then export back to matlab. This is annoying!!!

I have one matrix <10x10> and I want to sort the first column in descending order while keeping it's respective values on the second column. Matlab seems to just sort each column individually.

Example:
matrix a
5 4
8 9
0 6
7 3

matrix b (output)
0 6
5 4
7 3
8 9

Upvotes: 2

Views: 15655

Answers (2)

sfstewman
sfstewman

Reputation: 5667

The sortrows answer by @chaohuang is probably what you're looking for. However, it sorts based on all columns. If you only want to sort based on the first column, then you can do this:

% sort only the first column, return indices of the sort
[~,sorted_inds] = sort( a(:,1) );

% reorder the rows based on the sorted indices
b = a(sorted_inds,:); 

Upvotes: 10

chaohuang
chaohuang

Reputation: 4115

Simply use b=sortrows(a); See here.

Upvotes: 4

Related Questions