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];
?
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.
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].
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 .
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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With