简体   繁体   English

matlab在单元格数组中查找子字符串

[英]matlab find substring in cell array

I try to find arrays in my cell which have to part 'HA' in their names. 我试图在我的单元格中找到必须在其名称中包含“HA”的数组。 I found a function here but it does not work for my problem. 我在这里找到了一个功能,但它对我的问题不起作用。 My cell looks like this: 我的手机看起来像这样:

'HA1'   'HA1'   'HA1'   'HA1'   'HA1'
'HA2'   'HA2'   'HA2'   'HA2'   'HA2'
'HA3'   'HA3'   'HA3'   'HA3'   'HA3'
'HA4'   'HA4'   'HA4'   'HA4'   'HA4'
'HA5'   'HA5'   'HA5'   'HA5'   'HA5'
'HA6'   'HA6'   'HA6'   'HA6'   'HA6'
'HA7'   'HA7'   'HA7'   'HA7'   'HA7'
'HA8'   'WA1'   'WA1'   'WA1'   'WA1'
'HA9'   'WA2'   'WA2'   'WA2'   'WA2'
'HA10'  'WA3'   'WA3'   'WA3'   'WA3'
'HA11'  'WA4'   'WA4'   'WA4'   'WA4'
'DA1'   'WA5'   'WA5'   'WA5'   'WA5'
'DA2'   []  []  []  'WA6'
'DA3'   []  []  []  'WA7'
'DA4'   []  []  []  'WA8'
'DA5'   []  []  []  'WA9'
'DA6'   []  []  []  'WA10'
[]  []  []  []  'WA11'
[]  []  []  []  'WA12'

I tried this function: 我试过这个功能:

x = 'HA';
y = cellArray;
substrfind = @(x,y) ~cellfun(@isempty,strfind(y,x));
logicalArray = substrfind(x,y);

Im supposed to get a logical array as output which is really useful for my problem. 我应该得到一个逻辑数组作为输出,这对我的问题非常有用。 But instead I get this error message: " If any of the input arguments are cell arrays, the first must be a cell array of strings and the second must be a character array." 但我收到此错误消息:“如果任何输入参数是单元格数组,则第一个必须是字符串的单元格数组,第二个必须是字符数组。”

I do not understand what the error is because the first input y is a cell array and the second xa character. 我不明白错误是什么,因为第一个输入y是一个单元格数组,第二个是xa字符。

I hope you guys can help me with my problem! 我希望你们能帮助我解决我的问题! Thank you in anticipation! 谢谢你的期待! Best regards 最好的祝福

Suppose C is your cell array. 假设C是你的单元阵列。 Then one way to do what you want would be this: 然后一种方法来做你想要的是这样的:

>> C(cellfun('isempty', C)) = {''};
>> logicalArray = ~cellfun('isempty', strfind(C, 'HA'))

strfind does not accept cell arrays of which some values are not strings. strfind不接受某些值不是字符串的单元格数组。 Your cell array happens to have empty values, but of the wrong kind -- [] is double , not char . 你的单元格数组恰好有空值,但错误的类型 - []double ,而不是char That is the reason you get that error. 这就是你得到这个错误的原因。

So, I simply replace every empty double with the empty char ( '' ), and then use strfind . 所以,我只需用空的char( '' )替换每个空的double ,然后使用strfind

Another way around this problem: 解决此问题的另一种方法:

>> logicalArray = cellfun(@(x)~isempty(strfind(x,'HA')), C)

but that is a lot slower. 但那要慢得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM