Reputation: 938
Given two numpy arrays (matrices)
A = np.linspace(1,9,9).reshape(3,3)
B = np.linspace(10,18,9).reshape(3,3)
We can combine them into a block diagonal matrix by doing:
from scipy.linalg import block_diag
block_diag(A,B)
array([[ 1., 2., 3., 0., 0., 0.],
[ 4., 5., 6., 0., 0., 0.],
[ 7., 8., 9., 0., 0., 0.],
[ 0., 0., 0., 10., 11., 12.],
[ 0., 0., 0., 13., 14., 15.],
[ 0., 0., 0., 16., 17., 18.]])
I am wondering if there is a straight forward way to define the following 'overlap' type matrix from A and B:
array([[ 1., 2., 3., 0.],
[ 4., (10.+5.)/2, (6.+11.)/2, 12.],
[ 7., (13.+8.)/2, (14.+9.)/2, 15.],
[ 0., 16., 17., 18.]])
So instead of placing A, B on the diagonal, we allow them to overlap to some degree, and elements in the overlap get averaged. In general, I'd like to specify the degree of overlap, so in this example the degree of overlap would be 2. I'd also ideally want to keep the sparse structure, as opposed to constructing the entire array.
Upvotes: 0
Views: 81
Reputation: 15071
Here's a way to do it for regular matrices:
overlap = 2
pad_A = len(A)-2
pad_B = len(B)-2
ZerosA = np.zeros((pad_A,pad_A))
ZerosB = np.zeros((pad_B,pad_B))
Sum = block_diag(A,ZerosA) + block_diag(ZerosB,B)
Denom = block_diag(np.ones_like(A),ZerosA)+block_diag(ZerosB,np.ones_like(B))
Out = np.where(Denom>0, Sum/Denom, 0)
Output:
array([[ 1. , 2. , 3. , 0. ],
[ 4. , 7.5, 8.5, 12. ],
[ 7. , 10.5, 11.5, 15. ],
[ 0. , 16. , 17. , 18. ]])
Again no experience with sparse matrices, but I would assume the structure of this solution should translate well to sparse representation given it just uses block definitions too?
Upvotes: 0