MATLAB Answers

Add SINGLE element to array or vector

7,026 ビュー (過去 30 日間)
Pedro GUillem
Pedro GUillem 2016 年 5 月 12 日
コメント済み: Image Analyst 2020 年 12 月 20 日 20:59
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?

  0 件のコメント



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
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]
x = [x, newval]
For a column vector:
x = [x; newval]

  6 件のコメント

表示 3 件の古いコメント
Image Analyst
Image Analyst 2018 年 12 月 2 日
Please state exactly what you'd like as an output. It sounds like you want a string (character array).
Mathi 2019 年 11 月 5 日
The above code is working perfectly. Thank you.
Stefano Cardarelli
Stefano Cardarelli 2020 年 3 月 26 日
also this works for me, is basically direct indexing:
x(end+1) = newval


その他の回答 (3 件)

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 日

  0 件のコメント


Tue Dao
Tue Dao 2020 年 12 月 20 日 19:45
Which option is equivalent to the expression below:
a|b & c|~d

  1 件のコメント

Image Analyst
Image Analyst 2020 年 12 月 20 日 20:59
I think you "Answered" this 4 year old question when you actually meant to post a NEW question of your own.


Community Treasure Hunt

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

Start Hunting!

Translated by