Filtering a matrix with different rules for each columns

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.

 Accepted Answer

Vectorized with logical indexing:
C = AB(AB(:,1)>0.5 & AB(:,2)<0.2,:);

4 Comments

Small correction if Thomas is looking to retain all columns:
C = AB(AB(:,1)>0.5 & AB(:,2)<0.2,:);
Sean and Evan:
Thank you both for the answer. It works wonderfully.
Thank you Sean and Thomas! I have been looking for something like this. I was wondering how I can do this when my data is a Table (with names and numbers). For example, I have a table with student names and grades, and I would like to filter the table in the same way.
Thanks in advance.
Jason

Sign in to comment.

More Answers (1)

Evan
Evan on 6 Dec 2012
Edited: Evan on 6 Dec 2012
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.

2 Comments

Thank you for the insight. As you said, I don't need the removing zero function but I think the information is definitely useful for me in future. Still have a lot to absorb with this program.
No problem, and best of luck in the future. :)

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!