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

Hik*_*est 2 matlab cell-array

使用Matlab,假设我们有一个单元阵列的单元阵列.例如:

C = { {'hello' 'there' 'friend'}, {'do' 'say' 'hello'}, {'or' 'maybe' 'not'} }
Run Code Online (Sandbox Code Playgroud)

我想找到C中包含字符串的所有单元格数组的索引'hello'.在这种情况下,我期望1和2,因为第一个单元阵列'hello'在第一个槽中,第二个单元阵列在第三个槽中.

我想象使用矩阵(一个简单的查找)会更容易一些,但出于教育目的,我也想学习使用单元格数组的过程.

提前谢谢了.

Div*_*kar 5

直截了当的方法

随着arrayfun-

out = find(arrayfun(@(n) any(strcmp(C{n},'hello')),1:numel(C)))
Run Code Online (Sandbox Code Playgroud)

随着cellfun-

out = find(cellfun(@(x) any(strcmp(x,'hello')),C))
Run Code Online (Sandbox Code Playgroud)

替代方法

您可以采用一种新的方法转换的输入cell array of cell arrays of stringscell array of strings,从而降低一个级别"cell hierarchy".然后,它执行strcmp并因此避免cellfunarrayfun可能使其比早先列出的方法更快.请注意,从性能的角度来看,如果输入单元阵列的每个单元格中的单元格数量变化不大,这种方法会更有意义,因为该转换会导致空单元格填充空白的2D单元阵列地方.

这是实施 -

%// Convert cell array of cell ararys to a cell array of strings, i.e.
%// remove one level of "cell hierarchy"
lens = cellfun('length',C)
max_lens = max(lens) 
C1 = cell(max_lens,numel(C))
C1(bsxfun(@le,[1:max_lens]',lens)) = [C{:}]  %//'

%// Use strsmp without cellfun and this might speed it up
out = find(any(strcmp(C1,'hello'),1))
Run Code Online (Sandbox Code Playgroud)

说明:

[1]将字符串的单元格数组的单元格数组转换为字符串的单元格数组:

C = { {'hello' 'there' 'friend'}, {'do' 'hello'}, {'or' 'maybe' 'not'} }
Run Code Online (Sandbox Code Playgroud)

转换为

C1 = {
    'hello'     'do'       'or'   
    'there'     'hello'    'maybe'
    'friend'         []    'not'  }
Run Code Online (Sandbox Code Playgroud)

[2]对于每一列,查找是否有any字符串hello并找到那些列IDs作为最终输出.


Ben*_*_11 5

这是一种使用正则表达式的方法,我认为它的效率远低于@Divakar的strcmp解决方案,但无论如何都可以提供信息.

regexp在单元阵列上运行,但由于C是单元阵列的单元阵列,我们需要使用cellfun得到单元阵列的逻辑单元阵列,之后我们cellfun再次使用它来获取匹配的索引.实际上我可能会使用不必要的步骤,但我认为这样更直观

码:

clear
clc

C = { {'hello' 'there' 'friend'}, {'do' 'say' 'hello'}, {'or' 'maybe' 'not'} }

CheckWord = cellfun(@(x) regexp(x,'hello'),C,'uni',false);
Run Code Online (Sandbox Code Playgroud)

CheckWord是一个包含0或1的单元格数组的单元格数组,具体取决于与字符串的匹配hello:

CheckWord = 

    {1x3 cell}    {1x3 cell}    {1x3 cell}
Run Code Online (Sandbox Code Playgroud)

为了让事情更清楚一点,让我们重新塑造CheckWord:

CheckWord = reshape([CheckWord{:}],numel(C),[]).'

CheckWord = 

    [1]    []     []
     []    []    [1]
     []    []     []
Run Code Online (Sandbox Code Playgroud)

由于CheckWord是一个单元格数组,我们可以使用cellfunfind查找非空单元格,即与匹配对应的单元格:

[row col] = find(~cellfun('isempty',CheckWord))

row =

     1
     2

col =

     1
     3
Run Code Online (Sandbox Code Playgroud)

因此,包含单词"hello"的单元格是第一个和第二个.

希望有所帮助!