Add SINGLE element to array or vector

6,118 次查看(过去 30 天)
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 个评论
Image Analyst
Image Analyst 2022-5-27
@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.

请先登录,再进行评论。

采纳的回答

Image Analyst
Image Analyst 2016-5-12
编辑:Image Analyst 2020-10-18
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 个评论
Mathi
Mathi 2019-11-5
The above code is working perfectly. Thank you.
Stefano Cardarelli
Stefano Cardarelli 2020-3-26
编辑:Stefano Cardarelli 2020-3-26
also this works for me, is basically direct indexing:
x(end+1) = newval

请先登录,再进行评论。

更多回答(2 个)

Dakota Jandek
Dakota Jandek 2020-4-7
x = [1, 2, 3]
x(length(x)+1) = 4
  2 个评论
Adrien Bouguerra
Adrien Bouguerra 2020-10-18
amazing method , really efficient thank u so much Dakota
Image Analyst
Image Analyst 2020-10-18
Or even better,
x = [1, 2, 3]
x(end+1) = 4

请先登录,再进行评论。


Youssef AAKAM
Youssef AAKAM 2019-10-13
x=[]
x=[x;'ysf']

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by