问题
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