Search code examples
matlabsortingcell-array

Sort a numbers of strings in a cell array (MATLAB)


I have an input cell-array:

 Input-cell = { 'ACGBF','BAFCEDG','FECA','AGDFB', 'GFCEABD', 'EDFCBAG'}

There are 6 strings in the above cell-array. I used the following command to sort each of the strings into the alphabet sequences as follows:

 datasort = cellfun(@sort, randata, 'Uniformoutput', 0); % 6 strings were changed

Now, I would like to change just n=4 strings and keep the left m=2 strings as oringinal. How can I do that ? The expected output will be :

    Output-cell = { 'ACGBF','BAFCEDG','ACEF','ABDFG', 'ABCDEFG', 'ABCDEFG'} 

Solution

  • What you need to do is simply pass-in the the part of the array you want to sort into your cellfun, and concatenate the rest, like so:

    randata = { 'ACGBF','BAFCEDG','FECA','AGDFB', 'GFCEABD', 'EDFCBAG'};
    n=4; 
    datasort = [randata(1:end-n) cellfun(@sort,randata(end-n+1:end),'Uniformoutput',0)];
    
    assert(isequal({ 'ACGBF','BAFCEDG','ACEF','ABDFG', 'ABCDEFG', 'ABCDEFG'},datasort));