Output of a vector which excludes the entries of the second vector

Hello,
Problem: Given two distinct integer vectors p and q. I'd like to get a new vector r, that is p excluding the entries of q.
For example,
p = [1 2 3 4 5 6 7 8], q = [2 5 7 9], then r = [1 3 4 6 8].
Hope to have a code in a singer line. Thanks.

 Accepted Answer

p = [1 2 3 4 5 6 7 8],
q = [2 5 7 9],
out=p(~ismember(p,q))

3 Comments

Thank very much. It works perfectly. I can now apply it to update my recent submission at FEX.

Sign in to comment.

More Answers (1)

r = setdiff(p, q);

3 Comments

Thank very much. It also works perfectly as Azzi's answer.
Note that the two answers are slightly different, having to do with the ordering of the outputs if the first vector is not sorted. setdiff() also has a 'stable' option to get the outputs in the original order.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!