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

Matlab find string within cell array

我有一个包含字符串和单元格的元胞数组(n×1 维),看起来像这样

{
{'r1'}     % -> cell content is in format 'char'
{'r2'}     % -> cell content is in format 'char'
{1x2 cell} % -> cell content is a cell array: [{'r1'}{'r2'}]
{'r3'}     % -> cell content is in format 'char'
{1x2 cell} % -> cell content is a cell array: [{'r1'}{'r3'}]
{1x2 cell} % -> cell content is a cell array: [{'r2'}{'r3'}]
{1x3 cell} % -> cell content is a cell array: [{'r1'}{'r2'}{'r3'}]
...
} 

我需要找到包含某些字符串的行索引,例如'r2'。我通常为此目的使用 strfind 如果单元格数组具有一致的格式(因此每个单元格中的 'char'-格式),它会很好用。

有什么方法可以将这个函数应用到上面显示的元胞数组结构中吗?

谢谢!

编辑:请查看附件中显示我正在使用的数据结构的三张图片,因为我不确定如何在文本中准确地 show/explain 元胞数组的层次结构和层。希望有所帮助。另附代码结果。

使用的代码:

change = 'r1.m';
srch = cellfun(@(x) strfind(x, change), strats, 'UniformOutput', false);
stringInRow = cellfun(@(x) numel(x) == 1 || (numel(x)>1)*numel(cell2mat(x))>0, srch);
rows = find(stringInRow);

您可以使用两个后续的 cellfun 调用:一个用于执行字符串搜索(逐个单元格),另一个用于对其求值(找到字符串 true 或未找到 false? )

%// example data
c{1} = 'r1';     
c{2} = 'r2';    
c{3}{1} = 'r1'; c{3}{2} = 'r2';
c{4} = 'r3';
c{5}{1} = 'r1'; c{5}{2} = 'r3';

%// example search
searchForString = 'r2';
srch = cellfun(@(x) strfind(x, searchForString), c, 'UniformOutput', false);
stringInRow = ...
  cellfun(@(x) numel(x) == 1 || (numel(x)>1)*numel(cell2mat(x))>0, srch);
               %// ^-. short-circuit scalars here     ^
               %//                                    |
               %// since cell2mat is valid only for cells or empty arrays

结果 stringInRow:

stringInRow =

     0     1     1     0     0

如果您想明确列出行,您可以在 stringInRow 布尔向量

上使用 find
>> foundStringInRows = find(stringInRow)

foundStringInRows =

     2     3