开发者

ismember for string-matrix cell elements in MATLAB

开发者 https://www.devze.com 2023-03-07 06:45 出处:网络
ismember checks for cell-array or matrix elements.How do we check for string-numeric elements together?Please see below:

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开发者_JAVA技巧 func was used) but still can't hit the right answer. The desired answer is:

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


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消