Checking for existence of row in a matrix

102 ビュー (過去 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?
  1 件のコメント
KSSV
KSSV 2019 年 8 月 20 日
Read about ismember

サインインしてコメントする。

採用された回答

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 Center および File ExchangeImages についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by