Filtering a matrix with different rules for each columns
Afficher commentaires plus anciens
Beginner here,
With an array AB=100x2, I'm trying to retain rows that satisfy different rules for each column at the same time, i.e. AB(i,1)>0.5 and AB(i,2)<0.2
Based on my limited knowledge I've been able to come up with the following:
AB=rand(100,2);
for i=1:length(AB)
if AB(i,1)>0.5 & AB(i,2)<0.2;
C(i,:)=AB(i,:);
end
end
Problem with this is that the result contain zeros in the rows that do not meet this condition. How can I make sure that the resulting array is only as big as the number of rows that satisfy this condition? Or is there a simpler/different way to do this? TIA for your inputs.
Réponse acceptée
Plus de réponses (1)
Your indexing is causing the zeros. If, for example, rows 1 and 2 meet the criteria but row 3 doesn't, i = 4 on the next iteration. Your matrix C is, at that point, still 2 rows long. If row 4 meets the criterion, your code tries to place AB(4,:)'s values in C(4,:).
But there is, as of yet, no C(3,:). So a row of zeros is created in the same way that entering M(4) = 1 into the command window returns M = [0 0 0 1];
An inelegant but easy way to do it would be to remove [0 0] rows at the end. So just put a line at the end of your script that returns the rows where both values aren't zero:
M = C(sum(C,2)~=0,:);
You could modify your code to prevent this from happening altogether if you wish. Vectorizing the code could make the entire process possible in a single line (avoiding a for loop altogether) and is probably the best choice (see Sean's answer). However, the above works as a sloppy fix.
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!