Removing a specific number from vector

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.

Antworten (4)

Gurudatha Pai
Gurudatha Pai am 17 Jun. 2011

5 Stimmen

A = 4;
Z = [1 9 2 3 4 5]
Z1 = Z(find(Z~=A))
that should work
Walter Roberson
Walter Roberson am 17 Jun. 2011

3 Stimmen

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
Tiasa Ghosh am 25 Jul. 2018

1 Stimme

You can also use setdiff function.
a=4;
z=[1 9 2 3 4 5];
setdiff(z,a)

2 Kommentare

Gospel Oh
Gospel Oh am 15 Nov. 2018
If the function were to be put into MatLab, the answer actually comes out to be an ordered version, missig the a:
ans = 1 2 3 5 9
close, but not quite
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')

Melden Sie sich an, um zu kommentieren.

Richard Barrett-Jolley
Richard Barrett-Jolley am 13 Jul. 2018

0 Stimmen

Yes, that would work, but I would recommend simply:
Z=Z(Z~=A);

4 Kommentare

Walter Roberson
Walter Roberson am 17 Jul. 2018
I don't think I've seen anyone benchmark expressing as a subset copy, compared to expressing as a deletion such as I did.
Personally I find the deletion easier to read.
Walter Roberson
Walter Roberson am 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.
huda nawaf
huda nawaf am 7 Aug. 2022
HI
Im facing the same problem, but the size of A is more than one.
so Z=Z(Z~=A); does not work. Is there an alternative?
Thanks
Z = Z(~ismember(Z, A));

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Entering Commands finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 17 Jun. 2011

Kommentiert:

am 8 Aug. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by