直截了当的方法
与arrayfun -
out = find(arrayfun(@(n) any(strcmp(C{n},'hello')),1:numel(C)))
与cellfun -
out = find(cellfun(@(x) any(strcmp(x,'hello')),C))
替代方法
您可以采用一种新方法翻译 cell array of cell arrays of strings 的输入为cell array of strings,从而减少一个级别 "cell hierarchy"。然后,它执行strcmp,从而避免cellfun 或arrayfun,这可能使其比之前列出的方法更快。请注意,如果输入元胞数组的每个元胞中的元胞数量变化不大,这种方法从性能的角度来看会更有意义,因为这种转换会导致 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))
说明:
[1] 将字符串元胞数组的元胞数组转换为字符串元胞数组:
C = { {'hello' 'there' 'friend'}, {'do' 'hello'}, {'or' 'maybe' 'not'} }
转换成
C1 = {
'hello' 'do' 'or'
'there' 'hello' 'maybe'
'friend' [] 'not' }
[2] 为每一列查找是否有any 字符串hello 并找到那些列IDs 作为最终输出。