The question is published on by Tutorial Guruji team.
def getMatrixMinor(m,i,j): return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]
The above is the code that I find on the stack overflow in order to find the inverse of a matrix, however, I am really new in python. Can anybody explain the behind mechanism in order to construct a matrix of minor by using this code?
By the way, I’ve used this code and it works but I just don’t understand how it works.
Answer
Let’s start with the definition of (i,j)th
minor matrix of a matrix:
(i,j)th
minor of a matrix of sizen
is a smaller matrix of sizen-1
with thei'th
row andj'th
column deleted.
Now lets look at this python one liner:
[row for row in (m[:i] + m[i+1:])]
m[:i]
gives the first i
rows of m
(remember that we are representing a matrix as a list of rows, and adding two lists gives back a bigger list in python), now let’s look at another one liner:
row[:j] + row[j+1:]
This gives us all the elements of a row except the j'th
element (lst[a:b] gives a list with elements from lst
between a
and b
, with b
excluded)
Combine the above two and you get an expression which returns a new matrix with i'th row and j'th column excluded
:
def getMatrixMinor(m,i,j): return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]
Which is the minor matrix.