delete element from vector

8,968 views (last 30 days)
Majid Al-Sirafi
Majid Al-Sirafi on 24 Sep 2012
Commented: irvin rynning on 6 Dec 2021 at 0:46
Hi everyone
how can I delete element from vector .... for example
a=[1,2,3,4,5]
how can I delete 3 from above vector to be
a=[1,2,4,5]
thank you
majid
  8 Comments
Jeffrey Houston
Jeffrey Houston on 4 Jan 2021
Hi Hamna, sorry for the late response, but I'll answer for others anyways. The line of code below will do the trick for what you're asking for.
b = a(3)

Sign in to comment.

Accepted Answer

Daniel Shub
Daniel Shub on 24 Sep 2012
Edited: MathWorks Support Team on 9 Nov 2018
I can think of three ways that are all slightly different
a=[1,2,3,4,5];
If you want to get rid of all cases where a is exactly equal to 3
b = a(a~=3);
If you want to delete the third element
b = a;
b(3) = [];
or on a single line
b = a([1:2, 4:end]);
Or, as Jan suggests:
a = [2,3,1,5,4]
a(a == 3) = []
  7 Comments
Rik
Rik on 31 Mar 2021
@Anthony Dave Flags are not for personal bookmarks. Please remove your flag.

Sign in to comment.

More Answers (4)

Jan
Jan on 24 Sep 2012
Edited: Jan on 24 Sep 2012
a = [1,2,3,4,5]
a(3) = []
Or:
a = [2,3,1,5,4]
a(a == 3) = []
These methods are explained exhaustively in the "Getting Started" chapters of the documentation. It is strongly recommended to read them completely. The forum is not though to explain the fundamental basics. Thanks.
  3 Comments
irvin rynning
irvin rynning 4 minutes ago
unfortunately some of us prefer to use Matlab to solve problems in a timely manner, and cannot always engage in stackover-flow style plaudits on criticizing one's peers

Sign in to comment.


masoud sistaninejad
masoud sistaninejad on 23 Aug 2021
A = [ 1 2 3 4 5 6 7]
A = 1×7
1 2 3 4 5 6 7
B = [1 3 6]
B = 1×3
1 3 6
C = setdiff(A,B)
C = 1×4
2 4 5 7
  1 Comment
Andy Rojas
Andy Rojas on 24 Nov 2021 at 22:47
Thank you!

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 24 Sep 2012
a = a(abs(a - 3) > eps(100))
  1 Comment
Majid Al-Sirafi
Majid Al-Sirafi on 24 Sep 2012
than you very much

Sign in to comment.


Elias Gule
Elias Gule on 1 Dec 2015
% Use logical indexing
a = a(a~=3)
  2 Comments
Ntsakisi Kanyana
Ntsakisi Kanyana on 31 Mar 2020
Does it work on strings?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!