How can I delete rows in a matrix where two numbers exist side-by-side?

2 Ansichten (letzte 30 Tage)
I have a large matrix that has thousands of rows.
I need to delete the rows based on the following condition:
>>> if in a row, ith column is 2 and (i+1)th column is 3
e.g. Input matrix [1, 2, 1; 1, 2, 1; 2, 2, 3]
Expected output: [1,2,1;1,2,1]

Akzeptierte Antwort

lvn
lvn am 18 Mär. 2014
This should do the job. If you have a huge matrix and you want it to go faster, you will need to adapt this code to build up a vector with all rows that need deleting and do that once only (at the end).
A=[2,7,3;1, 2, 1; 1, 2, 1; 2, 2, 3; 1, 2, 1; 2, 3, 4]
rows=1;
while rows<=length(A)
if strfind(A(rows,:),[2 3])
A(rows,:)=[];
end
rows=rows+1;
end
A
Output:
A =
2 7 3
1 2 1
1 2 1
2 2 3
1 2 1
2 3 4
A =
2 7 3
1 2 1
1 2 1
1 2 1

Weitere Antworten (1)

Jos (10584)
Jos (10584) am 18 Mär. 2014
A = [2,7,3;1, 2, 1; 1, 2, 1; 2, 2, 3; 1, 2, 1; 2, 3, 4]
i = 1:size(A,2)-1
tf = A(:,i)==2 & A(:,i+1)==3 % true if i-the column is 2 and (i+1)th column is 3
A(any(tf,2),:) = [] % remove those rows

Kategorien

Mehr zu Standard File Formats finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by