# Add SINGLE element to array or vector

6.335 views (last 30 days)
Pedro GUillem on 12 May 2016
Commented: Image Analyst on 27 May 2022
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?
Image Analyst on 27 May 2022
@Anushalini Thiyagarajan I have no idea what you mean. Please ask your question in a new question (not here) after you read this:

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
or
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]
or
x = [x, newval]
For a column vector:
x = [x; newval]
Stefano Cardarelli on 26 Mar 2020
Edited: Stefano Cardarelli on 26 Mar 2020
also this works for me, is basically direct indexing:
x(end+1) = newval

Youssef AAKAM on 13 Oct 2019
x=[]
x=[x;'ysf']

Dakota Jandek on 7 Apr 2020
x = [1, 2, 3]
x(length(x)+1) = 4
##### 2 CommentsShowHide 1 older comment
Image Analyst on 18 Oct 2020
Or even better,
x = [1, 2, 3]
x(end+1) = 4