How to add matrices of different sizes in python? I have a 4 by 4 matrix of zeros and want to add a 2 by matrix at [0,0] and a 2 by 2 matrix at [1,1]
input:
Kglobal = np.zeros([4, 4])
Keq1 = np.array([2, -2], [-2, 2])
Keq2 = np.array([3, -3], [-3, 3])
Keq3 = np.array([6, -6], [-6, 6])
i tried:
Kglobal[0,0], Kglobal[1,1], Kglobal[2,2] = Keq1, Keq2, Keq3
The result needs to be
[2 -2 0 0
-2 2 3 -3 0
0 -3 3 6 -6
0 0 -6 6]
Thanks for the help!!
CodePudding user response:
Using the fact that we can assign to slices of NumPy arrays, we can do the following:
import numpy as np
Kglobal = np.zeros([4, 4])
Keq1 = np.array([[2, -2], [-2, 2]])
Keq2 = np.array([[3, -3], [-3, 3]])
Keq3 = np.array([[6, -6], [-6, 6]])
for idx, arr in enumerate([Keq1, Keq2, Keq3]):
row_shift, col_shift = arr.shape
Kglobal[idx:idx row_shift, idx:idx col_shift] = arr
print(Kglobal)
This outputs:
[[ 2. -2. 0. 0.]
[-2. 5. -3. 0.]
[ 0. -3. 9. -6.]
[ 0. 0. -6. 6.]]