MATLAB Answers

Add SINGLE element to array or vector

7 440 views (last 30 days)
I have a vector of the format:
x = [xval(1) xval(2) … xval(n)]
, and I want to add an element to the end, xval(n+1). How do I do that?


Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 12 May 2016
Edited: Image Analyst on 18 Oct 2020
For an existing vector x, you can assign a new element to the end using direct indexing. For example
x = [1 2 3]
x(4) = 4
x(end+1) = 4;
where "end" is a special keyword in MATLAB that means the last index in the array. So in your specific case of n elements, it would automatically know that "end" is your "n".
Another way to add an element to a row vector “x” is by using concatenation:
x = [x newval]
x = [x, newval]
For a column vector:
x = [x; newval]


Show 3 older comments
Image Analyst
Image Analyst on 2 Dec 2018
Please state exactly what you'd like as an output. It sounds like you want a string (character array).
Mathi on 5 Nov 2019
The above code is working perfectly. Thank you.
Stefano Cardarelli
Stefano Cardarelli on 26 Mar 2020
also this works for me, is basically direct indexing:
x(end+1) = newval

Sign in to comment.

More Answers (3)

Dakota Jandek
Dakota Jandek on 7 Apr 2020
x = [1, 2, 3]
x(length(x)+1) = 4


Adrien Bouguerra
Adrien Bouguerra on 18 Oct 2020
amazing method , really efficient thank u so much Dakota
Image Analyst
Image Analyst on 18 Oct 2020
Or even better,
x = [1, 2, 3]
x(end+1) = 4

Sign in to comment.

Youssef AAKAM
Youssef AAKAM on 13 Oct 2019


Sign in to comment.

Tue Dao
Tue Dao on 20 Dec 2020
Which option is equivalent to the expression below:
a|b & c|~d

  1 Comment

Image Analyst
Image Analyst on 20 Dec 2020
I think you "Answered" this 4 year old question when you actually meant to post a NEW question of your own.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!