Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Octave/Matlab: Adding new elements to a vector

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]; 

?

like image 401
URL87 Avatar asked Apr 24 '13 09:04

URL87


People also ask

How do you add elements to a matrix in MATLAB?

You can add one or more elements to a matrix by placing them outside of the existing row and column index boundaries. MATLAB automatically pads the matrix with zeros to keep it rectangular. For example, create a 2-by-3 matrix and add an additional row and column to it by inserting an element in the (3,4) position.

How do you add a vector in octave?

Simply type [1 2 3] at the prompt, followed by enter, and observe the output on the screen). Vector elements can also be entered separated by commas. For example, the command octave#:#> B = [0.1,2,5] will create the row vector B=[0.1 2 5].

How do you create an array in MATLAB?

To create an array with four elements in a single row, separate the elements with either a comma ( , ) or a space. This type of array is a row vector. To create a matrix that has multiple rows, separate the rows with semicolons. Another way to create a matrix is to use a function, such as ones , zeros , or rand .


2 Answers

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

like image 100
ThijsW Avatar answered Sep 21 '22 11:09

ThijsW


Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5; tic; x = rand(big,1); toc  x = zeros(big,1); tic; for ii = 1:big     x(ii) = rand; end toc  x = [];  tic;  for ii = 1:big     x(end+1) = rand;  end;  toc   x = [];  tic;  for ii = 1:big     x = [x rand];  end;  toc     Elapsed time is 0.004611 seconds.    Elapsed time is 0.016448 seconds.    Elapsed time is 0.034107 seconds.    Elapsed time is 12.341434 seconds. 

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds. Elapsed time is 0.009947 seconds. Elapsed time is 12.013875 seconds. Elapsed time is 12.165593 seconds. 

So I guess the speed advantage only applies to more recent versions of Matlab

like image 31
Dan Avatar answered Sep 19 '22 11:09

Dan