0

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{:}] .

1 Answer 1

4
  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);
    
Sign up to request clarification or add additional context in comments.

2 Comments

it works wonderful. another question : how can I access to the index of groups that contain 'remove'. for this example {1} {2} {3} contains 4.
You need to slightly modify the cellfun statement. For example, in the second approach it would be indices = find(cellfun(@(x) any(ismember(x,remove)), group))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.