Mike
Mike

Reputation: 21

MATLAB: how to delete elements of cell array A from cell array B?

I have two cell arrays of strings A and B that hold 60 and 400 subject names, respectively. All the subjects in cell array A are also in cell array B. What I would like to do is to delete the subjects listed in cell array A from cell array B to arrive at cell array C, that holds only the subjects I want to work with.

Upvotes: 2

Views: 4080

Answers (1)

gnovice
gnovice

Reputation: 125854

If you don't care about the result being sorted, you can use the function SETDIFF:

C = setdiff(B, A);

If you need the result in the same order as the original cell array B with the names from A removed, you can use the function ISMEMBER:

C = B(~ismember(B, A));

UPDATE: In newer versions of MATLAB, an additional argument has been added to SETDIFF to control the output element sorting. To maintain the original order, you can now do this:

C = setdiff(B, A, 'stable');

Upvotes: 7

Related Questions