How to filter data from multiple columns in a table

조회 수: 28 (최근 30일)
Jasmine Karim
Jasmine Karim 2018년 7월 9일
댓글: Paolo 2018년 7월 10일
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
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
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
Jasmine Karim
Jasmine Karim 2018년 7월 10일
That works, thank you!
Paolo
Paolo 2018년 7월 10일
If the answer solved your problem you can accept it :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by