Search code examples
stringmatlabcellconditional-statements

Deleting rows depending on two conditions - Matlab


I have a cell-type variable in Matlab alphabetically organized by FIRM.To each FIRM will correspond different and repeated C1s and C2s. For each FIRM I would like to delete repeated C2s (and respective row). The method would be to choose the row whose D2 that's the furthest from D1.

Initial cell:

FIRMS C1 C2 D1 D2 D3 'ACRO' '01464''043605' '19961231''19970212''19970401' 'ACRO' '01464''043605' '19961231''19970119''19970313' 'ACMJ' '00118''043605' '19961231''19970114''19970219' 'ACMJ' '01464''000151' '19961231''19970121''19970218' 'ACMJ' '00192''007960''19961231''19970523''19970728'

Final Cell:

'ACRO' '01464''043605' '19961231''19970212''19970401' 'ACMJ' '00192''007960''19961231''19970523''19970728'

Can anyone help me? Thanks a lot in advance.


Solution

  • Try this

    a = initial_cell;
    b = (abs(str2num(cell2mat(a(:,4))) - str2num(cell2mat(a(:,5)))));
    [temp ind1] = sort(b);
    s  = a(ind1(end:-1:1),:);
    [temp1 ind2 temp2] = unique(strcat(s(:,1),s(:, 3)));
    out_cell = s(ind2,:);
    

    output is

    out_cell = 
    
    'ACMJ'    '01464'    '000151'    '19961231'    '19970121'    '19970218'
    'ACMJ'    '00192'    '007960'    '19961231'    '19970523'    '19970728'
    'ACMJ'    '00118'    '043605'    '19961231'    '19970114'    '19970219'
    'ACRO'    '01464'    '043605'    '19961231'    '19970119'    '19970313'
    

    Note that out_cell is sorted by FIRM in this output, while it is not sorted by FIRM in the output stated in the question. Notify me if you need it that way.