How to compare a vector with a matrix rows ?
Show older comments
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)
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
Birdman
on 23 Mar 2018
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.
Birdman
on 23 Mar 2018
@Stephen: Exactly, that was my point.
>> 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
Herman Mahmoud
on 23 Mar 2018
0 votes
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!