Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a small matrix into a big one with numpy?

I'm trying to figure out how to take a small matrix (Matrix B below) and add the values into a larger matrix (Matrix A below) at a certain index. It seems like numpy would be a good option for this scenario but I can't figure out how to do it.

Matrix A:

[[0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0]]

Matrix B:

[[2, 3, 4]
 [5, 6, 7]
 [8, 9, 3]]

Desired end result:

[[0, 0, 0, 0, 0, 0]
 [0, 0, 2, 3, 4, 0]
 [0, 0, 5, 6, 7, 0]
 [0, 0, 8, 9, 3, 0]
 [0, 0, 0, 0, 0, 0]]
like image 876
bentedder Avatar asked Nov 02 '18 18:11

bentedder


People also ask

How do I append two matrices in Python using NumPy?

Use numpy. concatenate : >>> import numpy as np >>> np. concatenate((A, B)) matrix([[ 1., 2.], [ 3., 4.], [ 5., 6.]])

How do you expand a matrix in NumPy?

To expand the shape of an array, use the numpy. expand_dims() method. Insert a new axis that will appear at the axis position in the expanded array shape. The function returns the View of the input array with the number of dimensions increased.

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

Use the numpy. append() Function to Add a Row to a Matrix in NumPy. The append() function from the numpy module can add elements to the end of the array. By specifying the axis as 0, we can use this function to add rows to a matrix.


1 Answers

If you want to add B to A with the upper left-hand corner of B going to index (r, c) in A, you can do it using the index and the shape attribute of B:

A[r:r+B.shape[0], c:c+B.shape[1]] += B

If you want to just set the elements (overwrite instead of adding), replace += with =. In your particular example:

>>> A = np.zeros((5, 6), dtype=int)
>>> B = np.r_[np.arange(2, 10), 3].reshape(3, 3)

>>> r, c = 1, 2

>>> A[r:r+B.shape[0], c:c+B.shape[1]] += B
>>> A
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 2, 3, 4, 0],
       [0, 0, 5, 6, 7, 0],
       [0, 0, 8, 9, 3, 0],
       [0, 0, 0, 0, 0, 0]])

The indexing operation produces a view into A since it is simple indexing, meaning that the data is not copied, which makes the operation fairly efficient for large arrays.

like image 59
Mad Physicist Avatar answered Oct 27 '22 00:10

Mad Physicist