Search code examples
matlabmatchcellcell-array

Append new column based on a match between 2 cell variables in Matlab


I have a cell type variable A with 30000 rows and 20 columns:

A={12   1985    54,4678175115029    100 21  49  false   48,4    0   0   0 ...
     13 1985    46,4181591120695    189 22  44  false   51,8    0   0   0
     16 1985    53,0972274761171    183 22  12  false   48,6    0   0   0
     12 1986    43,1279032643053    173 22  14  false   48,6    0   0   0}

And a cell type variable B with 300 rows and 1 column:

B={17
  12
  74
  16
  117
  870
  ...}

In case variable B matches with the first row of A I am trying to add to A a row with the column of B. For instance in this example I would get:

  A={12 1985    54,4678175115029    100 21  49  false   48,4    0   0   0 12...
     13 1985    46,4181591120695    189 22  44  false   51,8    0   0   0 []
     16 1985    53,0972274761171    183 22  12  false   48,6    0   0   0 16
     12 1986    43,1279032643053    173 22  14  false   48,6    0   0   0 12}

It is possible there are repited values in A (see last row). In that case repeat the match again. I believe i have to use ismember but I am not being successful.

Thank you.


Solution

  • You were right with your intuition that ismember could be used here.

    See if this works for you -

    [v1,v2] = ismember(cell2mat(A(:,1)),cell2mat(B))
    A(v1,end+1) = B(v2(v2~=0))