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

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

采纳的回答

lvn
lvn 2014-3-18
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

更多回答(1 个)

Jos (10584)
Jos (10584) 2014-3-18
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

类别

Help CenterFile Exchange 中查找有关 Standard File Formats 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by