Matlab cellfun on function strfind

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

I want to use cellfun function on strfind function to find the index of each string in a cell array of string in another cell array of strings to exclude them from it.

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)) = []; 

There's error in the cellfun call line, how can I fix this?

回答1:

Here's a lovely one-liner:

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

Breakdown:

  • All the words/characters to search for are passed on to regexprep
  • This function replaces every occurrence of any word/character in the set given above, with the empty string ('').

It will automatically repeat this action on all elements in the cell-array string.

If you also wish to remove any empty strings from the cell string, do this after the command above:

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


回答2:

I think you're after this:

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

after which you can of course apply:

strings(idx) = []; 

Because you have two cell arrays which you want to cross-check (of which one is an array), you need to nest two cellfuns.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!