1
votes

ismember checks for cell-array or matrix elements. How do we check for string-numeric elements together? Please see below:

cell1 = {'netincome' [1] ; 'equity' [2] }  ;

cell2 = { 'cogs' [2222] [1] ; 'equity' [3501] [2] ; 

          'equity' [3333] [1] ; 'netincome' [1751] [1] } ;

This fails ->ismember(cell1(:,[1 2]), cell2(:,[1 3]) % I know why it fails.

Is there any way to match string elements and numeric elements from 2 cells? I tried using ismember independently (cell2mat func was used) but still can't hit the right answer. The desired answer is:

[1751 ; 3501] ; OR 'netincome' [1751] [1] ; 'equity' [3501] [2] 
1
A couple questions: Are the entries in cell1 and cell2 unique (i.e. no repeats)? Are the entries in cell1 guaranteed to have a match in cell2? - gnovice
Ans1. cell1 entries are unique when you consider col1 & col2 together. cell2 entries are NOT unique for col1 and col3. Certain rows can be repeated Ans2. Yes, always! - Maddy

1 Answers

1
votes

I don't think there's any good built-in solution for this situation. The best one I can think up at the moment is to create two nested loops to compare all the rows of each cell array, using the function ISEQUAL to do the comparisons:

index = zeros(size(cell1,1),1);
for row1 = 1:size(cell1,1)
  for row2 = 1:size(cell2,1)
    if isequal(cell1(row1,:),cell2(row2,[1 3]))
      index(row1) = row2;
      break
    end
  end
end

The result will be a set of match indices in the N-by-1 vector index, where N is the number of rows in cell1. If a row of cell1 can't be matched to the data in any row of cell2, then the corresponding entry of index will be 0. Indices of matches in index will preserve the original order of the data in cell1. Also, this code ignores multiple matches in cell2, returning only the index of the first match found and breaking the inner loop (which will potentially reduce the number of iterations needed).

Now you can index into cell2 to get the data corresponding to what's in cell1:

>> cell2(index,:)

ans = 

    'netincome'    [1751]    [1]
    'equity'       [3501]    [2]