finding an element in an array by comparing it with another array

后端 未结 1 1985
闹比i
闹比i 2021-01-22 12:47

I have a matrix

a = [ 1 \'cancer\'
      2 \'cancer\'
      3 \'cancer\'
      4 \'noncancer\'
      5 \'noncancer\' ]

I have another matrix wi

1条回答
  •  离开以前
    2021-01-22 13:11

    You can use ismember:

    a = { 1 'cancer'
          2 'cancer'
          3 'cancer'
          4 'noncancer'
          5 'noncancer' };
    
      b = [ 4
          5
          2 ];
    
     a(ismember([a{:,1}], b),:)
    

    This results in

    ans = 
    
        [2]    'cancer'   
        [4]    'noncancer'
        [5]    'noncancer'
    

    To display the results in the order specified by b use (as requested in a follow-up question: In the same order, finding an element in an array by comparing it with another array)

    [logicIDX, numIDX]  = ismember(b, [a{:,1}]);
    a(numIDX, :)
    

    This results in:

    ans = 
    
       [4]    'noncancer'
       [5]    'noncancer'
       [2]    'cancer' 
    

    0 讨论(0)
提交回复
热议问题