Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab find substring in cell array

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'

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 x a character.

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

like image 285
cacá Avatar asked Feb 14 '23 17:02

cacá


1 Answers

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

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)

but that is a lot slower.

like image 130
Rody Oldenhuis Avatar answered Feb 17 '23 10:02

Rody Oldenhuis