How to filter data from multiple columns in a table
32 views (last 30 days)
Show older comments
I'm not sure where I am going wrong because I have tried this several ways/am trying to learn along the way. I have a dataset that looks something like:
MT= {7 3 '15' 'response1';
7 4 '25' 'response2';
7 6 '15' 'response1';
7 7 '15' 'response2';
7 9 '25' 'response1'};
etc.
I am creating a loop that will run through the entire length and select the ENTIRE row IF column 3 = '15' and column 4 = 'response2', and so forth. I'm having trouble telling it to pull the entire row and put it into a matrix. I suspect it's something to do with the '15' and 'response' being characters?
This is what I am trying:
for x = 1:length(MT)
if (MT{x,3} == '15') && (MT{x,4} == 'response1') || ...
(MT{x,3} == '25') && (MT{x,4} == 'response2')
AC(x,1) = MT{x,1}
AC(x,2) = MT{x,2}
AC(x,3) = MT{x,3}
AC(x,4) = MT{x,4}
end
end
What am I doing wrong? Thank you in advance.
1 Comment
Yash Trivedi
on 9 Jul 2018
Hi Jasmine,
According to the code example that you've posted, MT is a MATLAB cell array. MT{x, 3} or MT{x, 4} are char arrays, so the == will do a character by character comparison and will return a vector of logical variables. I suggest that you use the strcmp method to compare them as it returns only a scalar logical.
Accepted Answer
Paolo
on 9 Jul 2018
Edited: Paolo
on 9 Jul 2018
No loop is necessary. Yes, you need to use strcmp for the comparison.
MT= {7 3 '15' 'response1';
7 4 '25' 'response2';
7 6 '15' 'response1';
7 7 '15' 'response2';
7 9 '25' 'response1'};
A = MT(strcmp(MT(:,3),'15') & strcmp(MT(:,4),'response1'),:);
B = MT(strcmp(MT(:,3),'25') & strcmp(MT(:,4),'response2'),:);
>>A
A =
{[7]} {[3]} {'15'} {'response1'}
{[7]} {[6]} {'15'} {'response1'}
>>B
B =
{[7]} {[4]} {'25'} {'response2'}
2 Comments
More Answers (0)
See Also
Categories
Find more on Calendar in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!