I have a matrix A
like
1 2 3 4 5
6 7 8 9 0
and I want to expand it with a row of ones to get
1 1 1 1 1
1 2 3 4 5
6 7 8 9 0
I create the row of ones with
col_size = size(A, 2);
ones_row = ones(1, col_size);
How can I add my ones_row
to the matrix?
The rbind() function adds additional row(s) to a matrix in R.
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.
Once you have A
and ones_row
you do:
[ones_row; A]
This returns the following.
1 1 1 1 1
1 2 3 4 5
6 7 8 9 0
I would probably do it as suggested in the previous answer, however in some cases (when the matrix sizes get very big), a more memory friendly solution would be to preallocate a matrix of the correct size and use indexing to put the existing values in the correct place:
A = [ 1 2 3 4 5; 6 7 8 9 0 ];
B = ones(size(A) + [1,0]); % Create an array of ones that is one row longer
B(2:end,:) = A; % Replace the elements of B with elements from A
The reason why I say this is more memory friendly is because when we create a row of ones we need to allocate memory for a vector, and then when we concatenate we need to allocate memory again for the result of the concatenation. When we use indexing, there's no need to allocate an intermediate vector. It isn't really important in this example, but can be quite significant for larger matrices or operations performed thousands of times.
There's also a useful function in the Image Processing Toolbox - padarray
:
A = [ 1 2 3 4 5; 6 7 8 9 0 ];
B = padarray(A,[1 0],1,'pre');
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