aaa
aaa

Reputation: 251

Take out elements from a vector that meets certain condition

I have two vectors, A = [1,3,5] and B = [1,2,3,4,5,6,7,8,9,10]. I want to get C=[2,4,6,7,8,9,10] by extracting some elements from B that A doesn't have.

I don't want to use loops, because this is a simplified problem from a real data simulation. In the real case A and B are huge, but A is included in B.

Upvotes: 1

Views: 48

Answers (2)

Divakar
Divakar

Reputation: 221574

One approach with unique, sort and diff -

C = [A B];

[~,~,idC] = unique(C);
[sidC,id_idC] = sort(idC);

start_id = id_idC(diff([0 sidC])==1);
out =  C(start_id(start_id>numel(A)))

Sample runs -

Case #1 (Sample from question):

A =
     1     3     5
B =
     1     2     3     4     5     6     7     8     9    10
out =
     2     4     6     7     8     9    10

Case #2 (Bit more generic case):

A =
    11    15    14
B =
    19    14     6     8     9    11    15
out =
     6     8     9    19

Upvotes: 0

David
David

Reputation: 8459

Here are two methods,

C=setdiff(B,A)

but if values are repeated in B they will only come up once in C, or

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

which will preserve repeated values in B.

Upvotes: 8

Related Questions