Checking for existence of row in a matrix

91 vues (au cours des 30 derniers jours)
Stewart Tan
Stewart Tan le 20 Août 2019
Commenté : Stewart Tan le 20 Août 2019
I have a sample matrix where:
my_mat = [1 2 4
5 3 1
6 9 7]
and what I'm trying to do is to check my_mat if there exist any rows where the first two element is equal to a new vector generated. If it does, then the third element will be incremented by 1. For example;
new_vec = [5 3]
Since [5 3] is an element in the second row as the first two element, then i would want to increment the third element of the row which is 1+1: hence i would get:
my_mat = [1 2 4
5 3 2
6 9 7]
Same goes, if i have another new vector generated:
new_vec = [6 9]
then the vector is found in the third row of my_mat, hence 7+1 for the third element:
my_mat = [1 2 4
5 3 2
6 9 8]
now, if the vec isn't found in any rows, then i would just add the new vec as another row in the matrix, with the third element initialized as 1
new_vec = [10 14]
my_mat = [my_mat;[new_vec,1]]
which would be:
my_mat = [1 2 4
5 3 2
6 9 8
10 14 1]
I would like to avoid using for loops since if the mat gets too large, searching each row with a for loop would result in slow performance. Is there any built in function i could use to perform this?
  1 commentaire
KSSV
KSSV le 20 Août 2019
Read about ismember

Connectez-vous pour commenter.

Réponse acceptée

Alex Mcaulley
Alex Mcaulley le 20 Août 2019
Try with this:
my_mat = [1 2 4
5 3 1
6 9 7];
new = [6 9];
Lia = ismember(my_mat(:,1:2),new,'rows');
if nnz(Lia)
my_mat(Lia,3) = my_mat(Lia,3) + 1;
else
my_mat(end+1,:) = [new,1];
end
  1 commentaire
Stewart Tan
Stewart Tan le 20 Août 2019
@Alex Mcaulley thank you! It works well!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Images 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!

Translated by