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 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
Voss
le 7 Mai 2022
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 commentaires
Voss
le 8 Mai 2022
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!