0

I have a 100x3 cell array, with each element being a string. Now I wish to sort it according to the 1st column. I can easily do this

sorted1 = sortrows(data, 1);

However, I don't want to stop here. I wish to further sort it according to the 2nd column. Of course, this sorting cannot destroy the 1st sorting. In other words, it is quite similar to how the dictionary is sorted.

How may I do this?

chappjc
  • 30,359
  • 6
  • 75
  • 132
Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174

1 Answers1

5

sortrows keeps sorting by other columns, if you specify them too:

>> data = {'banana','blue','cow'; 
           'zebra','ape','frog';
           'banana', 'apple', 'pear';
           'banana', 'apple', 'orange'};
>> sorted1 = sortrows(data, 1)
sorted1 = 
    'banana'    'blue'     'cow'   
    'banana'    'apple'    'pear'  
    'banana'    'apple'    'orange'
    'zebra'     'ape'      'frog'  
>> sorted1 = sortrows(data, [1 2])
sorted1 = 
    'banana'    'apple'    'pear'  
    'banana'    'apple'    'orange'
    'banana'    'blue'     'cow'   
    'zebra'     'ape'      'frog'  

Note that by excluding column 3 with [1 2], it doesn't waste time sorting by column 3 ('pear' still comes before 'orange').

chappjc
  • 30,359
  • 6
  • 75
  • 132
  • Does `sortrows(data)` do the same thing? – David Feb 26 '14 at 23:02
  • @David I am not sure, but even if it does, this is still useful, as the first 2 columns are enough for me. I won't waste the time sorting according to the 3rd column. :) – Sibbs Gambling Feb 26 '14 at 23:03
  • 1
    @FarticlePilter Right, I updated the answer with a `[1 2]` column specification. – chappjc Feb 26 '14 at 23:04
  • @chappjc Sorry, I meant in general. Are there any reasons for using `sortrows(data,1:length(data))` rather than just `sortrows(data)`? I understand that in this case you want `sortrows(data,[1 2])`, but if you wanted to use all columns, is there a difference? – David Feb 26 '14 at 23:05
  • @David I get what you are saying, and I don't think it really makes sense to do `1:size(data,2)` now that you mention it. – chappjc Feb 26 '14 at 23:06
  • http://stackoverflow.com/questions/22055139/matlab-textscan-reading-result-is-a-nested-cell-array Can you please help with this as well? I really appreciate that! – Sibbs Gambling Feb 26 '14 at 23:08
  • @chappjc OK cool, it just struck me as a little odd and I wondered whether there was something clever going on. Thanks! – David Feb 26 '14 at 23:08