I am trying to solve a mathematical problem related to matrices using numpy as shown below:
I am really finding it hard to represent this kind matrix structure using numpy. I really donot want to type these values because I want to understand how this kind of structures are represented using python. Consider the empty places as zero. Thank you for great help.
The matrix has to be decomposed into several parts. First, the middle region forms a block diagonal matrix, where each block is a 4x4 Toeplitz matrix.
# makes a shifted diagonal matrix
def E(n, v, k):
return v * np.eye(n, k=k)
def toeplitz_block(n, v_list, k_list):
return sum(E(n, v, k) for v, k in zip(v_list, k_list))
Then we can do the following:
n = 4 # size of block
m = 3 # how many blocks
# Make block diagonal matrix A
A = np.zeros((m, n, m, n))
u, v = np.diag_indices(m)
A[u, :, v, :] = toeplitz_block(n, [-1, 3, -1], [-1, 0, 1])
A = A.reshape(m * n, m * n)
print(A.astype(int))
# Output:
[[ 3 -1 0 0 0 0 0 0 0 0 0 0]
[-1 3 -1 0 0 0 0 0 0 0 0 0]
[ 0 -1 3 -1 0 0 0 0 0 0 0 0]
[ 0 0 -1 3 0 0 0 0 0 0 0 0]
[ 0 0 0 0 3 -1 0 0 0 0 0 0]
[ 0 0 0 0 -1 3 -1 0 0 0 0 0]
[ 0 0 0 0 0 -1 3 -1 0 0 0 0]
[ 0 0 0 0 0 0 -1 3 0 0 0 0]
[ 0 0 0 0 0 0 0 0 3 -1 0 0]
[ 0 0 0 0 0 0 0 0 -1 3 -1 0]
[ 0 0 0 0 0 0 0 0 0 -1 3 -1]
[ 0 0 0 0 0 0 0 0 0 0 -1 3]]
To get the final desired matrix, we can just add another Toeplitz matrix that has the diagonal of -1s.
B = A + E(n * m, -1, -4)
print(B.astype(int))
# Output:
[[ 3 -1 0 0 0 0 0 0 0 0 0 0]
[-1 3 -1 0 0 0 0 0 0 0 0 0]
[ 0 -1 3 -1 0 0 0 0 0 0 0 0]
[ 0 0 -1 3 0 0 0 0 0 0 0 0]
[-1 0 0 0 3 -1 0 0 0 0 0 0]
[ 0 -1 0 0 -1 3 -1 0 0 0 0 0]
[ 0 0 -1 0 0 -1 3 -1 0 0 0 0]
[ 0 0 0 -1 0 0 -1 3 0 0 0 0]
[ 0 0 0 0 -1 0 0 0 3 -1 0 0]
[ 0 0 0 0 0 -1 0 0 -1 3 -1 0]
[ 0 0 0 0 0 0 -1 0 0 -1 3 -1]
[ 0 0 0 0 0 0 0 -1 0 0 -1 3]]