How to find the position of a given vector A in a matrix M when the size of vector A is smaller than the columns of that matrix?
1 次查看(过去 30 天)
显示 更早的评论
采纳的回答
Voss
2022-5-7
Here's one way, assuming you want to match A or its reverse and that the elements have to be contiguous:
M = [46 58 50
46 41 49
15 2 1
16 2 15
21 16 15
14 16 20
16 23 20];
A = [15 2];
pos = [];
for ii = 1:size(M,1)
if ~isempty(strfind(M(ii,:),A)) ... % check if A is in row ii of M
|| ~isempty(strfind(M(ii,:),A(end:-1:1))) % or the reverse of A is in row ii of M
pos(end+1) = ii;
end
end
disp(pos)
3 个评论
Voss
2022-5-8
Ah, ok. I wasn't sure if elements from A that are separated in a row of M should be counted as a match, which is why I said "that the elements have to be contiguous" in my answer.
Your solution will work if the elements in a given row of M are distinct, but consider the following situation, where I've modified row 3 of M:
M = [14 5 4
16 4 3
16 4 16
33 29 26
35 38 40
2 16 3]
A = [16 3]
pos = find(sum(ismember(M,A),2)==2)
Now row 3 is counted because it has two 16's. To handle that situation correctly, you can do this instead:
pos = [];
for ii = 1:size(M,1)
if all(ismember(A,M(ii,:)))
pos(end+1) = ii;
end
end
disp(pos);
This counts a row of M if all elements of A are found in that row. It doesn't take into account the order of the elements of A in the row of M, as my initial answer did.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!