Octave/Matlab:向向量添加新元素 [英] Octave/Matlab: Adding new elements to a vector
问题描述
有一个向量 x
并且我必须添加一个元素 (newElem
) .
Having a vector x
and I have to add an element (newElem
) .
-
x(end+1) = newElem;
和
x = [x newElem];
?
推荐答案
x(end+1) = newElem
更健壮一些.
x = [x newElem]
仅在 x
是行向量时有效,如果它是列向量 x = [x;newElem]
应该使用.x(end+1) = newElem
但是,适用于行向量和列向量.
x = [x newElem]
will only work if x
is a row-vector, if it is a column vector x = [x; newElem]
should be used. x(end+1) = newElem
, however, works for both row- and column-vectors.
不过一般来说,应该避免增长向量.如果您经常这样做,它可能会使您的代码陷入困境.想一想:增加一个数组涉及分配新空间、复制所有内容、添加新元素和清理旧的烂摊子……如果您事先知道正确的大小,那就太浪费时间了:)
In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)
这篇关于Octave/Matlab:向向量添加新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!