Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a row to a matrix

Tags:

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?

like image 773
andandandand Avatar asked Nov 06 '11 03:11

andandandand


People also ask

How do you add a row to a matrix in R?

The rbind() function adds additional row(s) to a matrix in R.

How do you add data 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.


2 Answers

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
like image 195
David Alber Avatar answered Oct 09 '22 01:10

David Alber


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');
like image 26
Dev-iL Avatar answered Oct 09 '22 01:10

Dev-iL