且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

八度/Matlab:向向量添加新元素

更新时间:2023-11-07 12:46:16

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 :)