Octave/Matlab: Adding new elements to a vector

URL87 picture URL87 · Apr 24, 2013 · Viewed 153.5k times · Source

Having a vector x and I have to add an element (newElem) .

Is there any difference between -

x(end+1) = newElem; 

and

x = [x newElem];

?

Answer

ThijsW picture ThijsW · Apr 24, 2013

x(end+1) = newElem is a bit more robust.

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