Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a vector to matrix rows in numpy

Tags:

Is there a fast way in numpy to add a vector to every row or column of a matrix.

Lately, I have been tiling the vector to the size of the matrix, which can use a lot of memory. For example

    mat=np.arange(15)     mat.shape=(5,3)      vec=np.ones(3)     mat+=np.tile(vec, (5,1)) 

The other way I can think of is using a python loop, but loops are slow:

    for i in xrange(len(mat)):         mat[i,:]+=vec 

Is there a fast way to do this in numpy without resorting to C extensions?

It would be nice to be able to virtually tile a vector, like a more flexible version of broadcasting. Or to be able to iterate an operation row-wise or column-wise, which you may almost be able to do with some of the ufunc methods.

like image 541
user1149913 Avatar asked Aug 15 '12 14:08

user1149913


People also ask

How do you add a vector to a NumPy matrix?

Use the numpy. add() Function to Perform Vector Addition in NumPy. The add() function from the numpy module can be used to add two arrays. It performs addition over arrays that have the same size with elements at every corresponding position getting summed up.

How do you add rows to a matrix?

Adding Row To A Matrix We use function rbind() to add the row to any existing matrix. To know rbind() function in R simply type ? rbind() or help(rbind) R studio, it will give the result as below in the image.

Can you add a vector to a matrix?

For matrices or vectors to be added, they must have the same dimensions. Matrices and vectors are added or subtraced element by corresponding element.

How do you add a value to a matrix in Python?

Adding to an array using array moduleBy using append() function : It adds elements to the end of the array. By using insert() function : It inserts the elements at the given index. By using extend() function : It elongates the list by appending elements from both the lists.


1 Answers

For adding a 1d array to every row, broadcasting already takes care of things for you:

mat += vec 

However more generally you can use np.newaxis to coerce the array into a broadcastable form. For example:

mat + np.ones(3)[np.newaxis,:] 

While not necessary for adding the array to every row, this is necessary to do the same for column-wise addition:

mat + np.ones(5)[:,np.newaxis] 

EDIT: as Sebastian mentions, for row addition, mat + vec already handles the broadcasting correctly. It is also faster than using np.newaxis. I've edited my original answer to make this clear.

like image 113
JoshAdel Avatar answered Sep 22 '22 14:09

JoshAdel