简体   繁体   中英

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]]

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.

You can pad the b array into the same shape with a. numpy.pad

import numpy as np

a = np.array([[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]])

b = np.array([[2,3,4],
 [5,6,7],
 [8,9,3]])


b = np.pad(b, ((1,1) , (2,1)), mode = 'constant', constant_values=(0, 0))

print(a+b)

After padding b will be

[[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]]

a+b will be

[[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 ((1,1) , (2,1)) means you add 1 row on top, one row on bottom, 2 columns on left, 1 columns on right. All added row and columns are zeros because of mode = 'constant', constant_values=(0, 0) .

So you can input the index you want to add the matrix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM