Search code examples
arraysmatlabsortingcell

sorting cell array based on column (double not char) values


I have a 3x1 cell array A which includes:

10.2  
15.2  
7.2   

and another 3x1 cell Array B includes:

m
l
s

I would like to join these into a new 3x2 cell Array C including:

10.2  m
15.2  l
7.2   v

then I want to sort C according to the values of the first column which is supposed to be

7.2 v
10.2 m
15.2 l

what I did so far to do this is as follows:

C=A;
C(:,2)=B;
C=sortrows(C,1);

However the result is:

10.2 m
15.2 l
7.2 v

I think the reason is that it considers the numbers in the first column as characters and the way it sorts them is by looking at the digits of each number one by one from the left.. thus 10.2 is less than 7.2.
I am looking for a way to assign the numbers as numbers to C so when I sort them it considers them as numbers not characters. I tried to use cell2mat when assigning A and B to C but did not work. I have searched the web for this but could not find what I am looking for.

Thank you!


Solution

  • This would do what you need:

    >>
    C = cell(numel(A),2);
    [Sorted_A, Index_A] = sort(cell2mat(A));
    C(:,1) = num2cell(Sorted_A);
    C(:,2) = B(Index_A);
    

    For example, for the input as follows:

    >>
    A = {10.2; 15.2; 7.2};
    B = {'m'; 'l'; 'v'};
    

    The result would be:

    >> C
    
    C = 
    
        [ 7.2000]    'v'
        [10.2000]    'm'
        [15.2000]    'l'
    

    EDIT

    It seems that in your case, the input array A is not just a cell array of numbers, but a cell array of strings; i.e., for example,

    >>
    A = {'10.2'; '15.2'; '7.2'};
    

    In this case, you need to make the following changes:

    1. Use str2double(A) instead of cell2mat(A)
    2. Use strtrim(cellstr(num2str(Sorted_A))) instead of num2cell(Sorted_A);

    Your final code will now be:

    >>
    C = cell(numel(A),2);
    [Sorted_A, Index_A] = sort(str2double(A));
    C(:,1) = strtrim(cellstr(num2str(Sorted_A)));
    C(:,2) = B(Index_A);
    

    For example, for the input as follows:

    >>
    A = {'10.2'; '15.2'; '7.2'};
    B = {'m'; 'l'; 'v'};
    

    The result would be:

    >> C
    
    C = 
    
        '7.2'     'v'
        '10.2'    'm'
        '15.2'    'l'