Sort row by row cell matrix?
1 次查看(过去 30 天)
显示 更早的评论
Hello all, I tried to sort a cell matrix, row by row with sortrows function but this sort all matrix instead of each row.
I would like to sort:
a=[{'c'},{'b'},{'a'};
{'c'},{'a'},{'b'};
{'c'},{'b'},{'a'};]
With this output:
a=[{'a'},{'b'},{'c'};
{'a'},{'b'},{'c'};
{'a'},{'b'},{'c'};]
Could someone help me?
Thank you!!!
2 个评论
Guillaume
2015-12-4
What a strange way to declare the cell array.
a = {'c', 'b', 'a';
'c', 'a', 'b';
'c', 'b', 'a'}
requires less typing. But if all cells are just a single character then using a char array:
a = ['cba'; 'cab'; 'cba']
is even simpler.
回答(3 个)
the cyclist
2015-12-4
sort(a')'
5 个评论
the cyclist
2015-12-4
To be clear, this was the exact code I ran:
a=[{'c'},{'b'},{'a'}; {'f'},{'d'},{'e'}; {'b'},{'c'},{'a'};];
sort(a')'
the cyclist
2015-12-5
As verified by Image Analyst and myself:
a = {'home', 'apple', 'tiger'; 'onion', 'house', 'knife'; 'sugar', 'money', 'rich'} sorted_a = sort(a')'
yields, as expected:
a = 'home' 'apple' 'tiger' 'onion' 'house' 'knife' 'sugar' 'money' 'rich'
sorted_a = 'apple' 'home' 'tiger' 'house' 'knife' 'onion' 'money' 'rich' 'sugar'
Image Analyst
2015-12-4
Perhaps this:
a=[{'c'},{'b'},{'a'};
{'c'},{'a'},{'b'};
{'c'},{'b'},{'a'};]
charArray = cell2mat(a)
% Sort each row individually
for row = 1 : size(charArray, 1);
[~, sortOrder] = sort(charArray(row, :));
charArray(row,:) = charArray(row, sortOrder);
end
% Print to command window
charArray
The end is a character array, which is a heck of a lot easier to deal with than a cell array.
2 个评论
Image Analyst
2015-12-4
Guillaume has given two one-liners - one for cell arrays and one for character arrays. I suggest you avoid cell arrays unless you really need them (like for mixed data types or strings that are not all the same length), and in this situation you don't need cell arrays at all.
Guillaume
2015-12-4
a = {'c', 'b', 'a';
'c', 'a', 'b';
'c', 'b', 'a'}
num2cell(sort(cell2mat(a), 2))
is all that is needed. But as stated, if a was a char array to start with:
a = ['cba'; 'cab'; 'cba'];
sort(a, 2)
is so much simpler.
3 个评论
the cyclist
2015-12-4
Can someone besides me please verify that
sort(a')'
does work for this case as well? I'm baffled why Diego can't just use this very simple solution.
Image Analyst
2015-12-4
Verfied:
a = {'home', 'apple', 'tiger'; 'onion', 'house', 'knife'; 'sugar', 'money', 'rich'} sorted_a = sort(a')'
a = 'home' 'apple' 'tiger' 'onion' 'house' 'knife' 'sugar' 'money' 'rich' sorted_a = 'apple' 'home' 'tiger' 'house' 'knife' 'onion' 'money' 'rich' 'sugar'
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!