Numpy: A function that creates a block matrix
Let’s say I have a dimension k
. What I’m looking for is a function that takes k
as input and returns the following block matrix.
Let I be the k-dimensional
identity matrix and 0
be the k-dimensional zero square matrix
Namely:
def function(k):
...
return matrix
function(2) -> np.array([I, 0])
function(3) -> np.array([[I,0,0]
[0,I,0]])
function(4) -> np.array([[I,0,0,0]
[0,I,0,0],
[0,0,I,0]])
function(5) -> np.array([[I,0,0,0,0]
[0,I,0,0,0],
[0,0,I,0,0],
[0,0,0,I,0]])
That is, the
output is a (k-1,k) matrix where the identity matrix is on the diagonal elements and the zero matrix is elsewhere.
I tried :
I
know how to create any individual row, I just can’t think of a way to put it into a function so that it takes dimension k
, and spits out the matrix I need
For example
np.block([[np.eye(3),np.zeros((3, 3)),np.zeros((3, 3))],
[np.zeros((3, 3)),np.eye(3),np.zeros((3, 3))]])
will be the desired output at k=3
scipy.linalg.block_diag It looks like it’s probably on the right track….
Solution
IMO, np.eye
already has everything you need because you can define the number of rows and columns separately.
So your function should look like
def fct(k):
return np.eye(k**2-k, k**2)