How do I remove rows if the sum of its cells equals to a specific value?

조회 수: 1 (최근 30일)
Leonardo Rodrigues
Leonardo Rodrigues 2017년 9월 30일
댓글: Jan 2017년 9월 30일
I have a big matrix with lots of useless rows ( when the sum of the row = -104000 ). How do I remove these rows based on this condition?
I tried this:
v=1:1:NUMBER_OF_ROWS;
if sum(A(v,:)) == -104000;
A(v,:) = [];
end
but it didn't work.
  댓글 수: 2
Jan
Jan 2017년 9월 30일
"Didn't work" is a weak description of the problem. Prefer to explain, what you observe.
Leonardo Rodrigues
Leonardo Rodrigues 2017년 9월 30일
It doesn't remove any row, it just shows the value of each cell in the matrix.

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2017년 9월 30일
편집: Jan 2017년 9월 30일
This works fluently without a loop:
toDelete = (sum(A, 2) == -104000);
A(toDelete, :) = [];
Your loop has the problem, that if a v.th row has been removed, processing the (v+1).th row will leave out the new v.th row. In addition you cannot run the loop until NUMBER_OF_ROWS, if you have removed rows already, because then A(NUMBER_OF_ROWS, :) does not exist anymore.
A (bad) solution would be to run the loop in backward direction:
for v = NUMBER_OF_ROWS:-1:1
if sum(A(v,:)) == -104000
A(v,:) = [];
end
end
But then Matlab has to create a new array every time a row is removed and this requires a huge amount of resources. This is equivalent to letting an array grow iteratively. Search for "pre-allocation" in this forum.
  댓글 수: 3
Image Analyst
Image Analyst 2017년 9월 30일
Av is the name of the array - what you called A.
Since "remove" is a built-in method (function), you might want to call it "rowsToDelete" instead of "remove".
Jan
Jan 2017년 9월 30일
"Av" was a typo, use "A" instead.
@Image Analyst: Thanks for pointing this out. I did not use containers.Map yet, so I was not aware that "remove" is a Matlab command now.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Marco
Marco 2017년 9월 30일
Hello Leonardo, you can use the "removerows" function: https://it.mathworks.com/help/nnet/ref/removerows.html
You can see also this link: https://it.mathworks.com/matlabcentral/answers/41762-delete-row-from-matrix
BR Marco

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by