How to find a certain string in a cell with variable size

Suppose we have a varying sized cell array, e.g:
TempCell = {{'a1','a2'},{'a3','a4','a8','a7'},{'a2','a1'},{'a9'}};
Now, how to find indices of a certain string (like 'a1') in TempCell and remove those arrays which contain that specific string?:
TempCell = {{'a3','a4','a8','a7'},{'a9'}};
I assume Cellfund would be of use, but I could not find any efficient way to use it (I mean without any loop). Any help is more than welocme!

 채택된 답변

Stephen23
Stephen23 2015년 10월 25일
편집: Stephen23 2015년 10월 25일
>> TempCell = {{'a1','a2'},{'a3','a4','a8','a7'},{'a2','a1'},{'a9'}};
>> out = TempCell(~cellfun(@(c)any(strcmp('a1',c)),TempCell));
>> out{:}
ans =
'a3' 'a4' 'a8' 'a7'
ans =
'a9'
Using a loop will actually be more efficient (and faster), but cellfun is much more compact code.

댓글 수: 2

Dear Stephen, Thanks for your answer. I thought cellfun is faster than a loop. Using cellfun in form of cellfun('mean'...) rather than cellfun(@mean...) seems more efficient, am I right?
Stephen23
Stephen23 2015년 10월 25일
편집: Stephen23 2015년 10월 25일
Usually a loop is faster, but cellfun is often neater.
You can try cellfun('mean',...) if you wish to, but this is not supported by the cellfun documentation: " Backward Compatibility cellfun accepts function name strings for function func, rather than a function handle, for these function names: isempty, islogical, isreal, length, ndims, prodofsize, size, isclass. Enclose the function name in single quotes." For these (and only these) listed operations one can call cellfun with the string: this is faster than calling cellfun with a function handle.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2015년 10월 25일
And the llop method:
pattern = 'a1';
TempCell = {{'a1','a2'},{'a3','a4','a8','a7'},{'a2','a1'},{'a9'}};
remove = false(size(TempCell));
for k = 1:numel(TempCell)
remove = any(strcmp(TempCell{k}, pattern));
end
TempCell(remove) = [];

댓글 수: 1

Dear Jan, Thanks for your answer. I think the correct form is as follow:
...
remove (k) = any...
...
FinalAns = TempCell(~remove);

댓글을 달려면 로그인하십시오.

카테고리

태그

질문:

2015년 10월 25일

편집:

2015년 10월 25일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by