How to filter data from multiple columns in a table

35 ビュー (過去 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 Center および File ExchangeCalendar についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by