For the following code:
country(1).name='USA';
country(2).name='Spain';
country(3).name='France';
% descending order
[~,index]=sort({country.name},'descend');
country=country(index);
for i=1:3
fprintf('name = %s\n', country(i).name)
end
I have the following strange error when using sort for cells such as string name in descending order:
Error using sort
DIM and MODE arguments not supported for cell arrays.
Error in sandbox (line 43)
[~,index]=sort({country.name},'descend');
It works nicely for string if is ascending order, and with numerical value it works either ascending and descending sorting.
According to what I searched online and tried, the syntax would be expected to be working. But it is not working only for string in descending order.
The output for descending order should look like:
name = USA
name = Spain
name = France
Any suggestions or idea on how to get it fixed for the type of data struct with cells that my program is using? All comments are warmly welcome!
Per the documentation (and the error message):
direction
is not supported whenA
is a cell array, that is,sort
only sorts in ascending order.
You can use flip
to work around this:
country(1).name='USA';
country(2).name='Spain';
country(3).name='France';
% descending order
[~,index]=sort({country.name});
country=flip(country(index));
for i=1:3
fprintf('name = %s\n', country(i).name)
end
Which prints:
name = USA
name = Spain
name = France