Search code examples
matlabmatchcell

Append a column to a cell based on a condition in Matlab


I have a cell type variable A with 500000 rows and 3 columns. Example:

A={1994 'AACE'  2071
1994    'AACE'  30677
1994    'AAC'   1541
1994    'AACCU' 2027 …}

And a second cell type variable B with 100000 rows and 3 columns. Example:

B={1994 'AA'    31
1994    'AAC'   4
1994    'AACE'  2
1994    'AADV'  4
1994    'AAIC'  8}

In case column 2 of A and B match I would like to add to A the value of column 3 of B. So my new A would be:

A={1994 'AACE'  2071 2
1994    'AACE'  30677 2
1994    'AAC'   1541 4
1994    'AACU'  2027 [] …}

This is what I have tried:

[c,d]=ismember(B(:,2),A(:,2))
A(nonzeros(d),4)=num2cell(B(c,3));

It does not give error, but it does not give the right solution. Not only does this code not copy the right values from the third column of B, as it doesn't consider repetitions.

Can someone help?


Solution

  • I think you mean "append" rather than "add".

    First, I would append a column to A. It will be the 4th column and each cell will initially be an empty double.

    A(:,4) = {[]};
    

    Next, considering only column 2 of A and B, locate any rows in A that have a value in B.

    [locA,locB] = ismember(A(:,2), B(:,2))
    

    And finally, replace the values:

    A(logical(locA),4) = B(locB(locB>0),3);
    
    A = 
    
        [1994]    'AACE'     [ 2071]    [2]
        [1994]    'AACE'     [30677]    [2]
        [1994]    'AAC'      [ 1541]    [4]
        [1994]    'AACCU'    [ 2027]     []