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 个)
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 个评论
Birdman
2018-3-23
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
2018-3-23
@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
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!