Delete rows in a matrix that contain ONLY a negative number
이전 댓글 표시
Hello
I've got a really large matrix (say 2000 x 3000) and I want to delete the rows that contain ONLY the negative number -999.
For example, I've got A = [5 3 -999 ; -999 -999 -999; 4 1 7 ; -999 -999 -999]
and I want my new matrix to be A = [5 3 -999 ; 4 1 7]
How can I do that?
Thanks!
채택된 답변
추가 답변 (3개)
Kye Taylor
2013년 1월 14일
편집: Kye Taylor
2013년 1월 14일
Try
isNegRow = all( A==-999, 2 );
A(isNegRow,:) = [];
Shashank Prasanna
2013년 1월 14일
편집: Shashank Prasanna
2013년 1월 14일
2 개 추천
If you don't want to use loops and keep it simple in a single line, I suggest logical indexing as follows:
A(all(A==-999,2),:)=[]
This should do the trick.
Amith Kamath
2013년 1월 14일
편집: Amith Kamath
2013년 1월 14일
I'm quite positive that this does the trick. There would probably be more optimal ways to do it!
X = 100.*rand(12,5); %for example.
X([2 5],:) = -999; % artificially create rows to remove.
i = 1;
while i <= size(X,1)
if(sum(X(i,:) == -999) == size(X,2))
X(i,:) = [];
else
i = i+1;
end
end
댓글 수: 3
Walter Roberson
2013년 1월 14일
No, that will not work if you have two consecutive rows to be deleted. Suppose rows 3 and 4 are to be deleted, then after you delete row 3, row 4 will move "up" to row 3, but then you add 1 to i and next examine what is now row 4 (which used to be row 5), failing to examine what is now at row 3. To fix this, you should only add 1 to i if you did not delete a row.
Amith Kamath
2013년 1월 14일
Edited: Thanks Walter! Didn't catch that case earlier! Your answer is much more elegant anyways.
James Tursa
2013년 1월 15일
편집: James Tursa
2013년 1월 15일
Using a loop in this manner is very bad for performance. At each row that is deleted, potentially huge amounts of data will need to be copied. The same data can end up being copied many, many times. For a large matrix with many rows being deleted, this can easily result in a performance hit that is one or more orders of magnitude slower than the other answers shown above. (This is basically the same problem as increasing the size of an array in a loop). Best to get the indices of everything to be deleted first and then delete it all at once as shown above.
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!