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일)
I trying to find the (row) postion of A = [15 2] in a matrix M.
M = [46 58 50
46 41 49
15 2 1
16 2 15
21 16 15
14 16 20
16 23 20]
The solution is pos = [3 4] as the vector A are in 3 and 4 rows of M.

채택된 답변

Voss
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 4
  댓글 수: 3
GANESH R
GANESH R 2022년 5월 8일
I found the answer.
M =
14 5 4
16 4 3
14 4 16
33 29 26
35 38 40
2 16 3
>> A
A =
16 3
>> pos = find(sum(ismember(M,A),2)==2)
pos =
2
6
Voss
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]
M = 6×3
14 5 4 16 4 3 16 4 16 33 29 26 35 38 40 2 16 3
A = [16 3]
A = 1×2
16 3
pos = find(sum(ismember(M,A),2)==2)
pos = 3×1
2 3 6
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);
2 6
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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by