如何使用特定列对矩阵进行排序,改变方向? 我试过这个,但是不行。
data:
A1 5 P19
A2 7 P45
A3 8 P7
[Y,I] = sort(data(:,3), 'descend');
B = data(Y,3);
我需要得到:
In Ascending
A3 8 P7
A1 5 P19
A2 7 P45
In descending:
A2 7 P45
A1 5 P19
A3 8 P7
感谢您的帮助。
答案 0 :(得分:3)
根据第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
根据第3栏没有“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
答案 1 :(得分:3)
假设您的数据是单元格矩阵:
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,:)
会给你:
'A3' [8] 'P7'
'A1' [5] 'P19'
'A2' [7] 'P45'
和
[~,idx2] = sort(temp,'descend')
A(idx2,:)
会给你:
'A2' [7] 'P45'
'A1' [5] 'P19'
'A3' [8] 'P7'
如果您的数据可以更改为:
A = {'A1' 5 'P19'; 'A2' 7 'P45'; 'A3' 8 'P07'};
它会让一切变得更轻松,就像每个人最初都想到的那样:
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'