How do i filter out certain values in a cell matrix using conditions for strings ?

25 ビュー (過去 30 日間)
I have a cell matrix-
x = { 1 2 'a' 'q' ; 2 3 'a' 'p'; 3 4 'a' 'q'; 5 6 'b' 'p' ; 7 8 'b' 'q' ;9 8 'b' 'q';};
or x =
1 2 a q
2 3 a p
3 4 a q
5 6 b p
7 8 b q
9 8 b q
I want to filter out all rows that have 'a' in the 3rd column and 'q' in the fourth. My result matrix should be-
result=
1 2 a q
3 4 a q
How do I do this?

採用された回答

ANKUR KUMAR
ANKUR KUMAR 2018 年 10 月 10 日
編集済み: ANKUR KUMAR 2018 年 10 月 10 日
You can use contains to find the required letter. contains gives true if the part of search string contains in the main string.
x(contains(x(:,3),'a') & contains(x(:,4),'q'),(3:4))
Better to use strcmp, as it check for complete string. strcmp checks for the complete strings. It gives true only when the complete string is present.
x(strcmp(x(:,3),'a') & strcmp(x(:,4),'q'),(3:4))
  3 件のコメント
ANKUR KUMAR
ANKUR KUMAR 2018 年 10 月 10 日
"(3:4) " is used because you wish to extract 3rd and fourth column as output. If you wish all, then use
x(strcmp(x(:,3),'a') & strcmp(x(:,4),'q'),:)
ans =
2×4 cell array
[1] [2] 'a' 'q'
[3] [4] 'a' 'q'
If data is on 3rd and 6th column, then use
x(strcmp(x(:,3),'a') & strcmp(x(:,6),'q'),:)
The above one gives output for complete columns.
ANKUR KUMAR
ANKUR KUMAR 2018 年 10 月 10 日
For more clarification, refer this,
x = { 1 2 'a' 6 8 'q' ; 2 3 'a' 2 5 'p'; 3 4 'a' 2 1 'q'; 5 6 'b' 1 2 'p' ; 7 8 'b' 1 1 'q' ;9 8 'b' 1 1 'q';}
x =
6×6 cell array
[1] [2] 'a' [6] [8] 'q'
[2] [3] 'a' [2] [5] 'p'
[3] [4] 'a' [2] [1] 'q'
[5] [6] 'b' [1] [2] 'p'
[7] [8] 'b' [1] [1] 'q'
[9] [8] 'b' [1] [1] 'q'
1)
x(strcmp(x(:,3),'a') & strcmp(x(:,6),'q'),:)
ans =
2×6 cell array
[1] [2] 'a' [6] [8] 'q'
[3] [4] 'a' [2] [1] 'q'
2)
x(strcmp(x(:,3),'a') & strcmp(x(:,6),'q'),[3,6])
ans =
2×2 cell array
'a' 'q'
'a' 'q'

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by