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?

1 commentaire

Image Analyst
Image Analyst le 27 Mai 2022
@Anushalini Thiyagarajan I have no idea what you mean. Please ask your question in a new question (not here) after you read this:
In the meantime, look at input functions such as readmatrix, importdata, dlmread, xlsread, fgetl, etc.

Connectez-vous pour commenter.

 Réponse acceptée

Image Analyst
Image Analyst le 12 Mai 2016
Modifié(e) : Image Analyst le 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]

6 commentaires

Weird Rando
Weird Rando le 12 Mai 2016
Modifié(e) : Weird Rando le 12 Mai 2016
Also, you need to initialise the variable x before your for loop.
x = [];
And inside the for loop you use Image Analyst code.
Pedro GUillem
Pedro GUillem le 12 Mai 2016
Thank you so much!!
Brent Vaalburg
Brent Vaalburg le 2 Déc 2018
How would you add a delimeter to this?
Image Analyst
Image Analyst le 2 Déc 2018
Please state exactly what you'd like as an output. It sounds like you want a string (character array).
Mathi
Mathi le 5 Nov 2019
The above code is working perfectly. Thank you.
Stefano Cardarelli
Stefano Cardarelli le 26 Mar 2020
Modifié(e) : Stefano Cardarelli le 26 Mar 2020
also this works for me, is basically direct indexing:
x(end+1) = newval

Connectez-vous pour commenter.

Plus de réponses (2)

Dakota Jandek
Dakota Jandek le 7 Avr 2020

2 votes

x = [1, 2, 3]
x(length(x)+1) = 4

2 commentaires

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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by