Sorting a cell array rows according to string column alphabetically

Hi everyone, a matlab beginner question :
I have a cell array like the following:
I want to sort the array rows alphabetically according to the first column. (and I want the first row to stay at the top as it is the header row)
I have tried to use sort and sortrows but I am getting the error : Error using sort Input argument must be a cell array of character vectors.
How can I sort this cell array?
Thanks

回答 (1 件)

Jos (10584)
Jos (10584) 2017 年 11 月 8 日

1 投票

Assuming your cell array is namens C:
C = {'c1' 'c2','c3' ; 'c' 1 2 ; 'a' 2 3 ; 'b' 3 4}
[~, ix] = sort(C(2:end,1)) % sort the first column from 2nd row onwards and get the indices
C(2:end,:) = C(ix+1,:) % do not forget to add a 1 :)

4 件のコメント

amonasro
amonasro 2017 年 11 月 8 日
編集済み: amonasro 2017 年 11 月 8 日
My cell array has the name output.
the declaration is like this: output = cell(100,14);
here is the error I am getting :
Error using sort Input argument must be a cell array of character vectors.
Error in myfunc (line 75) [~, ix] = sort(output(2:end,1));
Jos (10584)
Jos (10584) 2017 年 11 月 8 日
apparently some cells in the first column are not character vectors! You can check this using cellfun
tf = cellfun(@ischar, output(2:end,1))
What do want to do with these cells (rows)?
amonasro
amonasro 2017 年 11 月 8 日
the result of cellfun : K>> cellfun(@ischar, output(2:end,1))
ans =
13×1 logical array
0
0
0
0
0
0
0
0
0
0
0
0
0
But the assignments are like for example :
output{2,1} = {'lorem'};
or
fid = fopen(inputArg1, 'r');
tline = fgetl(fid);
C = strsplit(tline);
output{1, 4} = C(1);
What do you think is the problem here with the types?
Jos (10584)
Jos (10584) 2017 年 11 月 9 日
the content of the cells are not character arrays, but a cell containing a character array! See the differences between:
C1(1) = {'aaa'}
C2{1} = {'bbb'}
C3{1} = 'ccc'

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

質問済み:

2017 年 11 月 8 日

コメント済み:

2017 年 11 月 9 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by