# Add SINGLE element to array or vector

4.768 visualizzazioni (ultimi 30 giorni)
Pedro GUillem il 12 Mag 2016
Commentato: Image Analyst il 27 Mag 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?
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Image Analyst il 27 Mag 2022
@Anushalini Thiyagarajan I have no idea what you mean. Please ask your question in a new question (not here) after you read this:

Accedi per commentare.

### Risposta accettata

Image Analyst il 12 Mag 2016
Modificato: Image Analyst il 18 Ott 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]
##### 6 CommentiMostra 4 commenti meno recentiNascondi 4 commenti meno recenti
Mathi il 5 Nov 2019
The above code is working perfectly. Thank you.
Stefano Cardarelli il 26 Mar 2020
Modificato: Stefano Cardarelli il 26 Mar 2020
also this works for me, is basically direct indexing:
x(end+1) = newval

Accedi per commentare.

### Più risposte (2)

Dakota Jandek il 7 Apr 2020
x = [1, 2, 3]
x(length(x)+1) = 4
##### 2 CommentiMostra NessunoNascondi Nessuno
Adrien Bouguerra il 18 Ott 2020
amazing method , really efficient thank u so much Dakota
Image Analyst il 18 Ott 2020
Or even better,
x = [1, 2, 3]
x(end+1) = 4

Accedi per commentare.

Youssef AAKAM il 13 Ott 2019
x=[]
x=[x;'ysf']
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by