Reputation: 755
How can I sort a matrix using a specific column, with changing direction? I've tried this, but don't work.
data:
A1 5 P19
A2 7 P45
A3 8 P7
[Y,I] = sort(data(:,3), 'descend');
B = data(Y,3);
I need to get:
In Ascending
A3 8 P7
A1 5 P19
A2 7 P45
In descending:
A2 7 P45
A1 5 P19
A3 8 P7
Thanks for your help.
Upvotes: 1
Views: 155
Reputation: 112689
To sort in alphabetical order (not what you want) according to column 3:
[Y,I] = sort(data(:,3)); %// I gives the indices of sorted rows
B_asc = data(I,:); %// ascending
B_des = data(I(end:-1:1),:); %// descending
To sort in numerical order (which seems to be what you want) according to column 3 without the "P":
aux = strvcat(data(:,3)); %// put column 3 into matrix form, with trailing spaces
[Y,I] = sort(str2num((aux(:,2:end)))); %// convert to number and sort
B_asc = data(I,:); %// ascending
B_des = data(I(end:-1:1),:); %// descending
Upvotes: 3
Reputation: 25232
Assuming your data is a cell matrix:
A = {'A1' 5 'P19'; 'A2' 7 'P45'; 'A3' 8 'P7'};
temp = char(A(:,3));
temp = str2num(temp(:,2:end)); %get rid of the P
[~,idx1] = sort(temp,'ascend')
A(idx1,:)
will give you:
'A3' [8] 'P7'
'A1' [5] 'P19'
'A2' [7] 'P45'
and
[~,idx2] = sort(temp,'descend')
A(idx2,:)
will give you:
'A2' [7] 'P45'
'A1' [5] 'P19'
'A3' [8] 'P7'
If your data could be changed to:
A = {'A1' 5 'P19'; 'A2' 7 'P45'; 'A3' 8 'P07'};
it would make everything easier, as everybody initially thought here:
B = sortrows(A,3);
C = flipud(B);
B =
'A3' [8] 'P07'
'A1' [5] 'P19'
'A2' [7] 'P45'
C =
'A2' [7] 'P45'
'A1' [5] 'P19'
'A3' [8] 'P07'
Upvotes: 3