フィルターのクリア

Sorting a cell array of strings on dim

28 ビュー (過去 30 日間)
Noushin Farnoud
Noushin Farnoud 2015 年 12 月 15 日
編集済み: per isakson 2015 年 12 月 18 日
Hello All,
Is there a way I can sort along the 2nd dim of a cell array of strings? When I apply sort(x,2) on the example below, I receive the error msg: DIM and MODE arguments not supported for cell arrays.
I have:
x={'book','apple';'dood','tood';'soon','moon'}
x =
'book' 'apple'
'dood' 'tood'
'soon' 'moon'
I want to sort it on 2nd dim, so that I get:
sorted_x=
'apple' 'book'
'dood' 'tood'
'moon' 'soon'
I greatly appreciate your response.
Noushin

採用された回答

Guillaume
Guillaume 2015 年 12 月 17 日
Transpose the cell array, sort, and transpose back:
x = {'book','apple';'dood','tood';'soon','moon'};
sorted_x = sort(x')'
  2 件のコメント
Guillaume
Guillaume 2015 年 12 月 17 日
A generic version of this:
function sorted_c = sort_cell(c, dim)
%c: an Nd cell array
%dim: dimension to sort
permdims = 1:ndims(c);
permdims([1 dim]) = permdims([dim 1]);
sorted_c = permute(sort(permute(c, permdims)), permdims);
end
Stephen23
Stephen23 2015 年 12 月 17 日
+1 very tidy solution.

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

その他の回答 (1 件)

per isakson
per isakson 2015 年 12 月 15 日
編集済み: per isakson 2015 年 12 月 18 日
2015-12-18: Fixed a "typo". With R2013a.
Loop over all rows and concatenate
cac = arrayfun( @(jj) sort(x(jj,:)), (1:size(x,1)), 'uni', false )
sorted_x = cat( 1, cac{:} )
outputs
cac =
{1x2 cell} {1x2 cell} {1x2 cell}
sorted_x =
'apple' 'book'
'dood' 'tood'
'moon' 'soon'

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by