# Removing a specific number from vector

417 views (last 30 days)
Ulrik Nash on 17 Jun 2011
Commented: Walter Roberson on 30 Apr 2019
Hi Everyone,
Suppose I have the following
A = 4
and
Z = [1 9 2 3 4 5]
how do I remove the value A from Z, to get
Z = [1 9 2 3 5]
Regards,
Ulrik.

Gurudatha Pai on 17 Jun 2011
A = 4;
Z = [1 9 2 3 4 5]
Z1 = Z(find(Z~=A))
that should work

Walter Roberson on 17 Jun 2011
Z(Z==A) = [];
Warning: if you have floating point numbers instead of integers, you will usually need to compare with a tolerance instead of ==

Tiasa Ghosh on 25 Jul 2018
You can also use setdiff function.
a=4;
z=[1 9 2 3 4 5];
setdiff(z,a)
##### 2 CommentsShowHide 1 older comment
Paul Smits on 26 Apr 2019
You may pass 'stable' as additional input to setdiff, to prevent sorting:
a=4;
z=[1 9 2 3 4 5];
setdiff(z,a,'stable')

Richard Barrett-Jolley on 13 Jul 2018
Yes, that would work, but I would recommend simply:
Z=Z(Z~=A);
##### 2 CommentsShowHide 1 older comment
Walter Roberson on 30 Apr 2019
My testing suggests that Z=Z(Z~=A) is faster than deleting from Z, taking about 82% as long, at least for longer arrays.