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?
1 次查看(过去 30 天)
显示 更早的评论
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.
can anyone please help me to resolve this problem best regards,
0 个评论
采纳的回答
Guillaume
2018-5-14
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.
Anyway, to answer your question, it's simply:
T(any(flag > 2, 2), :) = [];
0 个评论
更多回答(1 个)
Bob Thompson
2018-5-14
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!