Checking for existence of row in a matrix

조회 수: 104 (최근 30일)
Stewart Tan
Stewart Tan 2019년 8월 20일
댓글: Stewart Tan 2019년 8월 20일
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
  댓글 수: 1
Stewart Tan
Stewart Tan 2019년 8월 20일
@Alex Mcaulley thank you! It works well!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Images에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by