Search code examples
matlabmatchcell

Create new variable if elements of different variables match in Matlab


I have 3 cell arrays: A that has 3 columns and 5000 rows. B that has 5 and 60 columns. C that has 4 columns and 500 rows. Sample of each varaible:

A= { 12 1999    41.2
     13 1999    47.7
     16 1999    52.7}

B= { 16 452 8   407 31
   1037 110 14  873 93
   1255 881 20  16  69}

C= { 13 1997    1999    2000
    141 1997    1999    2000
    174 1997    1999    2000}

If a value of the 1st column of A matches any value of the 1st column of B , I would like to add to A, columns 1, 4 and 5 of B plus a column only with the value 'one' . In case a value of the 1st column of A matches a value of the 1st column of C, I would like to add to A, columns 1 and 4 of C and an extra column with zeroes.

So the output would be:

Output= { 12    1999    41.2
          13    1999    47.7  13 2000 0    %match between A & C 
          16    1999    52.7  16 407 31 1} %match between A & B

Thank you.


Solution

  • It might not be the most elegant nor fastest solution, but i think it gets the job done. It assumes that the value can be only in B or in C but not in both (as it would be unclear what do to then, anyways).

    Bcol1 = [B{:,1}];
    Ccol1 = [C{:,1}];
    for r = 1:size(A,1)
        a = A{r,1};
        [inB, rowB] = ismember(a, Bcol1);
            if inB
                A{r, 4} = a;
                A{r, 5} = B{rowB,4};
                A{r, 6} = B{rowB,5};
                A{r, 7} = 1; 
            else  % not in B, maybe it is in C?
                [inC, rowC] = ismember(a, Ccol1);
                if inC
                    A{r, 4} = a;
                    A{r, 5} = C{rowC,4};
                    A{r, 6} = 0;
                end
            end
    end
    

    Oh, it changes A, if you need A to be unchanged, just start with a copy of A and modify it (instead of A itself). Best, Nras