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

조회 수: 2 (최근 30일)
sravan
sravan 2014년 3월 18일
답변: Jos (10584) 2014년 3월 18일
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