Search code examples
matlabcell

search in cell array in matlab


in matlab I create an cell that contains arrays with different size. for example:

group{1} = [2;3;4];
group{2} = [4;5];
group{3} = [2;4;11;5;7];

I'm going to find element and delete them. if I search for '4' then the result should be as below:

group{1} = [2;3];
group{2} = [5];
group{3} = [2;11;5;7];

how can I do it in matlab? I tried find, ismember, [group{:}] .


Solution

    1. You can use setdiff:

      remove = 4; %// may be a single value or a vector
      group = cellfun(@(x) setdiff(x,remove,'stable'), group, 'UniformOutput', 0);
      

      The 'stable'option in setdiff is used for keeping original element order.

    2. Alternatively, use ismember:

      remove = 4; %// may be a single value or a vector
      group = cellfun(@(x) x(~ismember(x,remove)), group, 'UniformOutput', 0);
      
    3. Possibly faster: if you only want to remove one value, simply use indexing:

      remove = 4; %// just one value
      group = cellfun(@(x) x(x~=remove), group, 'UniformOutput', 0);