Add SINGLE element to array or vector

Illustration
Jasper - 2020-11-19T11:27:31+00:00
Question: Add SINGLE element to array or vector

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?

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

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] 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!