Add SINGLE element to array or vector

조회 수: 6,395 (최근 30일)
Pedro GUillem
Pedro GUillem 2016년 5월 12일
댓글: Image Analyst 2022년 5월 27일
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