andandandand
andandandand

Reputation: 22260

Add a row to a matrix

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?

Upvotes: 20

Views: 100002

Answers (3)

Dev-iL
Dev-iL

Reputation: 24159

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');

Upvotes: 2

PyMatFlow
PyMatFlow

Reputation: 478

I can give a solution that can worked for any matrix.

suppose your matrix is A, A is m*n

n = size(A,2)

out = [ones(1,n);A]

This solution works for any matrix.

Upvotes: -1

David Alber
David Alber

Reputation: 18091

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

Upvotes: 42

Related Questions