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?
2 ビュー (過去 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 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!