Checking for existence of row in a matrix

90 次查看(过去 30 天)
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?

采纳的回答

Alex Mcaulley
Alex Mcaulley 2019-8-20
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by