2

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

1 Answer 1

1

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.]]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it works. Do you also know how to convert it into a 'for i in range' loop? With Kglobal being a matrix of (i+1, i+1) and there are Keqi arrays to add up
I suppose it's possible, but I think that isn't good style. If this is for practice, I will leave it as an exercise for you. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.