Add SINGLE element to array or vector

5.449 visualizaciones (últimos 30 días)
Pedro GUillem
Pedro GUillem el 12 de Mayo de 2016
Comentada: Image Analyst el 27 de Mayo de 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 comentario
Image Analyst
Image Analyst el 27 de Mayo de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Image Analyst
Image Analyst el 12 de Mayo de 2016
Editada: Image Analyst el 18 de Oct. de 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 comentarios
Mathi
Mathi el 5 de Nov. de 2019
The above code is working perfectly. Thank you.
Stefano Cardarelli
Stefano Cardarelli el 26 de Mzo. de 2020
Editada: Stefano Cardarelli el 26 de Mzo. de 2020
also this works for me, is basically direct indexing:
x(end+1) = newval

Iniciar sesión para comentar.

Más respuestas (2)

Dakota Jandek
Dakota Jandek el 7 de Abr. de 2020
x = [1, 2, 3]
x(length(x)+1) = 4
  2 comentarios
Adrien Bouguerra
Adrien Bouguerra el 18 de Oct. de 2020
amazing method , really efficient thank u so much Dakota
Image Analyst
Image Analyst el 18 de Oct. de 2020
Or even better,
x = [1, 2, 3]
x(end+1) = 4

Iniciar sesión para comentar.


Youssef AAKAM
Youssef AAKAM el 13 de Oct. de 2019
x=[]
x=[x;'ysf']

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by