Checking for existence of row in a matrix
30 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Stewart Tan
am 20 Aug. 2019
Kommentiert: Stewart Tan
am 20 Aug. 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?
Akzeptierte Antwort
Alex Mcaulley
am 20 Aug. 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!