问题
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.
来源:https://stackoverflow.com/questions/13289258/matlab-cellfun-on-function-strfind