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?

回答(3 个)

KSSV
KSSV 2018-3-23
编辑:KSSV 2018-3-23
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 个评论

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.
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.

请先登录,再进行评论。

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.

类别

在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by