Matlab在单元格数组中查找子字符串 [英] matlab find substring in cell array

查看:118
本文介绍了Matlab在单元格数组中查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在单元格中找到必须在名称中包含"HA"的数组.我在这里找到了一个函数,但不适用于我的问题. 我的手机看起来像这样:

I try to find arrays in my cell which have to part 'HA' in their names. 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'

我尝试了此功能:

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."

我不明白错误是什么,因为第一个输入y是一个单元格数组,第二个输入y是一个字符.

I do not understand what the error is because the first input y is a cell array and the second x a character.

我希望你们能帮助我解决我的问题! 谢谢您的期待! 最好的问候

I hope you guys can help me with my problem! Thank you in anticipation! Best regards

推荐答案

假设C是您的单元格数组.然后,做您想要的事情的一种方法是:

Suppose C is your cell array. Then one way to do what you want would be this:

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

strfind不接受某些值不是字符串的单元格数组.您的单元格数组碰巧具有空值,但是错误类型-[]double,而不是char.这就是您收到该错误的原因.

strfind does not accept cell arrays of which some values are not strings. Your cell array happens to have empty values, but of the wrong kind -- [] is double, not char. That is the reason you get that error.

因此,我只需将每个空的double替换为空的字符(''),然后使用strfind.

So, I simply replace every empty double with the empty char (''), and then use strfind.

解决此问题的另一种方法:

Another way around this problem:

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

但这要慢很多.

这篇关于Matlab在单元格数组中查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆