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

空扰寡人 提交于 2020-01-25 06:42:11

问题


I have a matrix

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

I have another matrix with values

b = [ 4
      5
      2 ]

Now I have to compare the b matrix values with values of a and the output should be

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

How can I do this in matlab ?


回答1:


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' 


来源:https://stackoverflow.com/questions/15250510/in-the-same-order-finding-an-element-in-an-array-by-comparing-it-with-another-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!