How to filter data from multiple columns in a table
32 次查看(过去 30 天)
显示 更早的评论
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 个评论
Yash Trivedi
2018-7-9
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.
采纳的回答
Paolo
2018-7-9
编辑:Paolo
2018-7-9
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calendar 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!