Matlab中cellfun函数在strfind函数中的应用

3
我想在另一个字符串的单元数组中使用strfind函数,通过cellfun函数查找每个字符串的索引,并将它们从该单元数组中排除。
strings = {'aaa','bbb','ccc','ddd','eee','fff','ggg','hhh','iii','jjj'};
excludedStrings = {'b','g','h'};
idx = cellfun('strfind',strings,excludedStrings);
idx = cell2mat = idx;
idx = reshap(idx,numel(idx),1);
idx = unique(idx);
strings(cell2mat(idx)) = [];

cellfun调用行中有错误,我该如何修复?


1
cellfun(@(x) strfind(strings,x), excludedStrings, 'UniformOutput', 0) 是否接近于您想要实现的目标? - Tim
2个回答

3

这里有一个很好的一行代码:

strings = regexprep(strings, excludedStrings, '');

细节解析:

  • 所有要搜索的单词/字符都被传递给regexprep函数。
  • 此函数将集合中每个单词/字符的任何出现替换为空字符串('')。

它会自动在单元格数组string中的所有元素上重复执行此操作。

如果您还希望从单元格string中删除任何空字符串,请在上述命令之后执行此操作:

strings = strings(~cellfun('isempty', strings));

2
不幸的是,如果excludedStrings包含多个字符的字符串,这种方法将无法正常工作... 我认为这个更好:strings = regexprep(strings, excludedStrings, '')。我还建议使用strings = strings(~cellfun(@isempty, strings))来删除“空”字符串。 - Eitan T
@EitanT:现在它可以工作了。关于你最后的陈述:我不确定OP是否真的想要那个... - Rody Oldenhuis
@EitanT:无论如何,总是使用cellfun('isempty', strings);它比cellfun(@isempty, strings)快10倍以上。 - Rody Oldenhuis
哦,我的最后一句话是基于以下 OP 的尝试:strings(cell2mat(idx)) = []; 关于 isempty,我刚刚测试了这两个函数,似乎 @isempty 要快大约两倍。你确定吗?(附言:我在 R2009a 上运行)... 无论如何加一。 - Eitan T
1
@EitanT: tic, for ii = 1:1e4, cellfun('isempty', strings); end; toc: 经过时间为0.056434秒。tic, for ii = 1:1e4, cellfun(@isempty, strings); end; toc: 经过时间为0.288836秒。也许不是10倍,但肯定快得多。更糟糕的是:tic, for ii = 1:1e4, cellfun(@(x)isempty(x), strings); end; toc: 经过时间为4.333200秒。 - Rody Oldenhuis
你说得对。在第一次迭代中,“@isempty”运行速度快了两倍。但在后面的迭代中,它的速度却慢了两倍……我以前也遇到过这些问题,但从未弄清原因。 - Eitan T

2
我认为您需要的是这个:

我想您可能需要以下内容:

idx = cellfun(@(str) any(cellfun(@(pat) any(strfind(str,pat)),excludedStrings)),strings)

idx =
    0     1     0     0     0     0     1     1     0     0

之后您当然可以应用:

strings(idx) = [];

因为您有两个需要交叉检查的单元数组(其中一个是数组),所以您需要嵌套两个cellfun函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接