Search code examples
arraysmatlabcell

Expand cell array iteratively


I have two cell arrays of different sizes and want to compare the cells in the first column of cellarray1 with the cells of the first column of cellarray2. If two cells are equal, take the information in the succeeding columns in that row in cellarray2 [could be a string, an int], and put it in cellarray1. What I need really is to know how to expand cellarray1 this flexibly.

The first columns of the two arrays are strings, Po001, Po002 etc... Cellarray1 will have two copies of each string, Po001, Po001, Po002, Po002 etc.
It's just that, I need to match the two arrays, if they match, I add the information in the other columns of cellarray2 which should be general, that is, the second column contains strings with two values e.g. Object1, Object2. The third column contains a 1 or 2. It just that I don't know how to expand rows of cellarrays with new cells, which after a whole for loop results in N new columns in cellarray1.

for ii = 1:length(cellarray2(:,1))
     for jj = 1:length(cellarray1(:,1))
         if strcmp(cellarray2{ii,1}, cellarray1{jj,1})
            % This seems to give the results I want but I 
            % dont know how to update the original cellarray1 
            % with this new row 
            [cellarray1(ii,1:end), cellarray2(jj,1:end)]
         end
     end
end

If this can be done it would be really good. Ideally, I would like to input the information from cellarray2, just after the first column of cellarray1. Like, create one column in cellarray1, for each column of cellarray2, and then input that information in cellarray1 if of course the comparison is true.

Best regards,
Granit


Solution

  • You can create a vector of indexes to indicate which rows from cellarray1(:,1) match with cellarray2(:,1) using cellfun , find and strcmp

    % Find the first location of match from cellarray1 in cellarray2
    locIdx = cellfun(@(x)find(strcmp(x,cellarray2(:,1)),1),cellarray1(:,1)); 
    

    Now you can copy columns from cellarray2 to cellarray1 like:

    cellarray1(:,2:end) = cellarray2(locIdx,2:end);  
    % I used 2:end assuming you want to copy only the non key columns
    

    Or if you want to append the columns into cellarray1:

    width2 = size(cellarray2,2);
    cellarray1(:,end+1:end+width2-1) = cellarray2(locIdx,2:end);