Reputation: 95
What's the proper way of checking if the first occurrence any element from a vector exists in a matrix? For example if I have
A = [1, 3]
and
B = [ 1, 2 ;
1, 4 ;
2, 3 ;
2, 4 ;
3, 4 ];
I should get something that returns the indices of matrix B where this condition is met. So for the example I should get.
indx = [1, 1]
I'm using MATLAB R2012a
Upvotes: 2
Views: 203
Reputation: 8518
Have to tried using strfind
command in Matlab.
You can try something like this :
res = strfind(B(:)',A)
This will give all the occurance of A in B. So, the first occurance would be res(1)
Hope it helps
Upvotes: 2
Reputation: 26069
you can use ismember
:
vec=ismember(A,B);
or
vec=ismember(B,A)
depends what you want exultantly (elements of A are found in B or vice versa). Then you can just
[row col]=find(vec,1, 'first')
to get the index position
Upvotes: 3
Reputation: 114786
In order to search for all elements of vector A
in matrix B
you may use bsxfun
:
tmp = bsxfun( @eq, B(:), A );
This comparison disregards the matrix shape of B
and treats it as a stack of elements. In your example B
has 10
elements and A
has 2
, therefore tmp
is a binary matrix of size 10x2
with true
wherever B
equals an elements of A
.
To find the first element of B
that equals any element of A
you simply do
idx = find( any( tmp, 2 ), 1, 'first' );
To convert the linear index idx
into a row-col pair into B
[r c] = ind2sub( size(B), idx );
Cheers!
Upvotes: 1