How to compare a vector with a matrix rows ?

Suppose I have a vector A= [1 2 3] and matrix B= [1 2 3 4 5; 1 5 6 7 8; 3 4 1 2 3]. I want to check if the vector A is exist or not in any of the matrix B rows? For this example, A is exists in the first and third and row….any help/suggestion?

Answers (3)

KSSV
KSSV on 23 Mar 2018
Edited: KSSV on 23 Mar 2018
Read about ismemebr
A= [1 2 3] ;
B= [1 2 3 4 5; 1 5 6 7 8; 3 4 1 2 3] ;
idx = sum(ismember(B,A),2)>=length(A) ;
1 says exists, 0 says no.

4 Comments

This answer does not work for the following case:
A=[1 2 3];
C=[1 1 1 1 1;1 2 3 4 5];
idx = sum(ismember(C,A),2)>=length(A);
Both output will be 1, however first row of C consists of only 1's.
Stephen23
Stephen23 on 23 Mar 2018
Edited: Stephen23 on 23 Mar 2018
ismember will not work if you want to detect the exact sequence 1,2,3, because ismember detects if each element of the first argument occurs anywhere in the second argument: the sequence is not taken into account. See my answer for code that detects that exact sequence.
@Stephen: Exactly, that was my point.

Sign in to comment.

Stephen23
Stephen23 on 23 Mar 2018
Edited: Stephen23 on 23 Mar 2018
It is actually very efficient to use strfind to locate an exact sequence inside a larger sequence:
>> A = [1,2,3];
>> C = [1,1,1,1,1;1,2,3,4,5];
>> X = strfind(num2cell(char(C),2),char(A));
>> X{:}
ans = []
ans = 1
Thanks guys for your replays(much appreciated). I think I find the solution. A= [1 2 3] ; B= [1 2 3 4 5; 1 5 6 7 8; 3 4 1 2 3] ; X = length(find(cell2mat(strfind(num2cell(char(B),2),char(A))))); The answer of X will be either 0 or greater than 0, 0 means A exist in B otherwise not exist.

Asked:

on 23 Mar 2018

Commented:

on 9 Mar 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!