可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 cellfun
s.