Sort all columns in a cell array with labels
古いコメントを表示
Hello everyone
I have the following cell array with text and numeric data:
>> M
M =
5×4 cell array
'' 'Ana' 'Delta' 'Oscar'
'B' [0.9058] [0.9058] [0.9058]
'C' [0.1270] [0.1270] [0.1270]
'D' [0.9134] [ 4] [ 2]
'E' [0.6324] [0.6324] [0.6324]
I would like to sort the data in columns 2, 3 and 4 in descending order (largest to smallest) but also with labels (column 1) and also with labels Ana, Delta and Oscar. I am aware that sortrows can be used for sorting data using a particular column, but I am not sure of the indexing for sortrows or an efficient way of sorting data in columns 2-4 in my cell array M and at the same time having labels next to them.
Thank you for your help.
Suha.
2 件のコメント
@Suha: you should really consider putting your data into a table, which natively store data with headers. Then you could apply lots of other functions to the data without having to worry about the first row and column being special cases, e.g. sorting the rows without requiring any indexing at all. It also stores the columns as arrays of an appropriate class, which makes working with the data much easier (putting lots of scalar numeric data into cells of a cell array just makes working with numeric data much more complex than it needs to be).
Suha
2018 年 2 月 13 日
採用された回答
その他の回答 (1 件)
Something like this?
[~,idx]=sort(cell2mat(M(2:end,2:end)),1,'descend');
M(sort(idx)+1,:)=M(idx+1,:)
or
[~,idx]=sortrows(M(2:end,2:end),'descend');
M(sort(idx)+1,:)=M(idx+1,:)
7 件のコメント
Suha
2018 年 2 月 13 日
Birdman
2018 年 2 月 13 日
What did you expect?
Suha
2018 年 2 月 13 日
Use this one,
[~,idx]=sort(cell2mat(M(2:end,2:end)),1,'descend');
M(sort(idx)+1,:)=M(idx+1,:)
Suha
2018 年 2 月 13 日
Birdman
2018 年 2 月 13 日
It worked perfectly in my case, where each column was sorted independently. Make sure you enter the code correctly, otherwise it should work. I can not attach a screenshot of it at the moment.
Suha
2018 年 2 月 14 日
カテゴリ
ヘルプ センター および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!