Search code examples
arraysmatlabcell-array

Sort a partition of an array in MATLAB


I have the following cell array A of size 1x9

A= {{'O1'} ,{'O1','O2','O3','O4'} ,{'O1','O3'} ,{'O1','O2','O3','O4'} , {},{'O1','O2','O3','O4'},{'O1','O3'},{'O1','O2','O3','O4'},{'O1','O2','O3','O4'}};

I want to sort a partition of this cell array starting the fifth element A{5:9} according to number of elements in the cell . I have tried the sort function as follows by didn't seems to work

[P,I] = sort(cellfun('length',A{5:9}));
A = A(I);

Also is there any way to keep track of the original indices of the cellarray after sorting ?


Solution

  • The sorting can be performed with the following code/

    A= {{'O1'} ,{'O1','O2','O3','O4'} ,{'O1','O3'} ,{'O1','O2','O3','O4'} , {},
    
    {'O1','O2','O3','O4'},{'O1','O3'},{'O1','O2','O3','O4'},{'O1','O2','O3','O4'}};
    disp('Before sorting')
    for ii = 1:numel(A)
        fprintf('%d: %s\n',ii, cell2str(A{ii}));
    end
    a=A(5:end);
    [P,I] = sort( cellfun(@(x) numel(x),a) );
    A(5:end) = a(I);
    clear a
    
    disp('After sorting')
    for ii = 1:numel(A)
        fprintf('%d: %s\n',ii, cell2str(A{ii}));
    end
    

    The mapping between the initial and final order of the cell array can be found using again I:

    originalOrder = 1:numel(A);
    finalOrder    = originalOrder;
    o = originalOrder(5:end);
    finalOrder(5:end) = o(I);
    clear o
    

    In your case: finalOrder = [1 2 3 4 5 7 6 8 9] The original position of cell 6in the modified A was finalOrder(6) = 7.