# How can i remove an entire row or column of a matrix if the elements of the matrix in the row or column of the matrix has been flagged with a certain number?

조회 수: 2(최근 30일)
Joseph 14 May 2018
Hi everyone, I have a matrix T(150,63051) and another matrix Flag(150,63051) which is the flag matrix for T. now I want to remove the entire row from matrix T if the corresponding elements (one or more than one element in the row) has flagged greater than 2 in the Flag matrix. here is my script:
for i=1:150
for j=1:length(T)
if (flag(i,j)>2)
T(i,:)=[];
end
end
end
but it gives me below error: Matrix index is out of range for deletion.

로그인 to comment.

### 채택된 답변

Guillaume 14 May 2018
First, a big warning, don't use length (for vectors numel is better) and certainly don't use length on a matrix. On a matrix use size with an explicit dimension. I also don't understand why you hardcode one dimension and retrieve the other, why not retrieve both:
for row = 1:size(T, 1)
for col = 1:size(T, 2)
is a lot safer than what you wrote. In any case, your loop code is very flawed. Never delete elements of an array when you iterate over it since your index gets out of sync with the actual rows. E.g, at i = 8 you delete row 8. row 9 is now row 8, row 10 is now row 9, etc. You then increase i, which becomes 9, and test flag(9, j) but row 9 of T is what used to be row 10. Out of sync.
T(any(flag > 2, 2), :) = [];

#### 댓글 수: 0

로그인 to comment.

Bob Nbob 14 May 2018
You can use smart indexing to complete this, but you're going to have a challenge with different size matrices if you aren't careful.
results = T(Flag>2);
This will produce a single column matrix with all elements of T where corresponding Flag elements are greater than 2. If you want to organize this into different columns then I would suggest keeping the first for loop you have set up.
for k = 1:150;
results(k,:) = T(k,B(k,:)>2); % Technically this looks row by row, rather than column by column.
end
The challenge with this setup is that any time the matrix needs to grow longer, because a previous row has less retained digits than the current, then an error will be thrown. Similarly, if a previous row was longer than the current then a dimension mismatch error will occur.
If you want to simply replace all values that don't meet the flag with blanks then I would suggest:
T(Flag<=2) = NaN;
This will prevent matrix sizing issues, and should solve the current issue you're having.

#### 댓글 수: 1

Joseph 14 May 2018
Thanks for your answer. I already used T(Flag<=2) = NaN; in my script. the problem is that it only makes the element with Flag>2=nan; however, I want to make the entire row nan or [] if even one element is (flag>2).

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.

Translated by