0

I am Stuggling with using the numpy.linalg.inv() function in Python. I populate 4 matrices by fetching certain elements in a nested for loop from a larger ZMatrix. As follows

#populating arrays for Zp
for k1 in range(3):
    for m1 in range(3):
        Za[k1][m1] = ZMatrix[k1][m1]

for k1 in range(3,4):
    for m1 in range(0,2):
        Zb[k1-3][m1] = ZMatrix[k1][m1]        

for k1 in range(0,2):
    for m1 in range(3,4):
        Zc[k1][m1-3] = ZMatrix[k1][m1]

for k1 in range(3,4):
    for m1 in range(3,4):
        Zd[k1-3][m1-3] = ZMatrix[k1][m1] 

Then I want to do the following calculation

ZpMatrix = Za-(Zb*np.linalg.inv(Zd)*Zc)

And it throws the error:

 LinAlgError: Singular matrix

How can I go about doing the calculations that I would like to, without this error.

Thank you very much

Robey Beswick
  • 31
  • 1
  • 5
  • 2
    You cannot invert Zd, simply because it is not invertible ; this is not a numpy.linalg issue. – P. Camilleri Oct 15 '15 at 10:32
  • What are the dimensions of `Zd`, and how did you create it? `range(3, 4)` is `[3,]`, so your loop to fill `Zd` has only executed *once*; all it did was `Zd[0][0] = ZMatrix[3][3]`. (By the way, for numpy `matrix` and `ndarray` objects, you can [and should] write `Zd[0, 0]` instead of `Zd[0][0]`.) – Warren Weckesser Oct 15 '15 at 10:42
  • I am trying to partition ZMatrix into the 4 different matrices and then use them to create ZpMatrix. – Robey Beswick Oct 15 '15 at 12:24
  • Zd is a 2 by 2 martix initialised as Zd= [[0 for x in range(2)] for x in range(2)] – Robey Beswick Oct 15 '15 at 12:25
  • Zmatrix is a 5 by 5 matrix and I wanted to put the 4 elements in the bottom left corner of the matrix into Zd. 3 and 4 that I use in the for loop is the 4th and 5th elements respectively. – Robey Beswick Oct 15 '15 at 12:28
  • Is my logic correct or have I made some sort of fundamental mistake? Thank you for the insight – Robey Beswick Oct 15 '15 at 12:29
  • 1
    The `range` function doesn't include the `stop` value in the sequence that it generates; see https://docs.python.org/2/library/functions.html#range. This is a pattern that you'll see throughout python and numpy. – Warren Weckesser Oct 15 '15 at 13:07
  • 1
    Instead of lists of lists for the matrices, you could use numpy arrays. E.g. `Zd = np.zeros((2, 2))`. Or even better, use a numpy array for `ZMatrix`, and then you can write `Zd = ZMatrix[3:, 3:]` (that's the lower right corner of `ZMatrix`, which is what it looks like your code tries to do). I recommend spending some time with a numpy tutorial. – Warren Weckesser Oct 15 '15 at 13:15

0 Answers0