八度/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 :)
这篇关于八度/Matlab:向向量添加新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!