1

I have run the below code in Python to generate minor of a matrix but am not getting the desired output.

import numpy as np 

m=np.array([(0,3,-1),(-1,11,-1),(2,-1,10)]) 

def getMatrixMinor(m,i,j): 

    return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]

getMatrixMinor(m,0,0)

If someone could pls suggest the corrections.

martineau
  • 119,623
  • 25
  • 170
  • 301
Ussu
  • 135
  • 1
  • 6
  • 1
    Is [Numpy Routine for Computing Matrix Minors?](https://stackoverflow.com/questions/3858213/numpy-routine-for-computing-matrix-minors) helpful? – Aviv Yaniv Sep 16 '20 at 18:19
  • 1
    look this: https://stackoverflow.com/questions/53934405/find-minor-matrix-in-python – Carlos Espinoza Garcia Sep 16 '20 at 18:20
  • Thanks for suggestions. I have ran the same code but not getting the desired outcome. – Ussu Sep 16 '20 at 18:21
  • 1
    @ussu Could you please add the outcome you are getting and the desired output? – Yash Sep 16 '20 at 18:22
  • @YashShah Link suggested by Avik works fine. – Ussu Sep 16 '20 at 18:24
  • 1
    When you add m[:i] to m[i+1:] what really happens is an addition of rows with broadcasting. If I understand correctly you wished to concatenate rows somehow. The ij-th minor will just delete the i-th row and j-th column so addition is probably not what you were looking for. – Gil Pinsky Sep 16 '20 at 18:27

2 Answers2

0

I hope this helps you:

def get_minor(numbers, i, j):
    minor = []

    for row in range(len(numbers[0])):

        col = 0
        min_row = []

        while (col < len(numbers[0])):

            row != i and col != j and min_row.append(numbers[row][col]) 
            col += 1
        
        len(min_row) and minor.append(min_row)

    return minor
fayez
  • 370
  • 1
  • 5
0

In case m is numpy array it can be done with this one-liner using np.ix_ and boolean indexing:

import numpy as np
i, j = 0, 2
m[np.ix_(np.arange(len(m))!=i, np.arange(len(m[0]))!=j)]

Note that:

  • looping numpy arrays is not efficient.

  • my code can be optimized further:

     def get_minor(m,i,j):
         X = np.ones(len(m)).astype(bool)
         Y = np.ones(len(m[0])).astype(bool)
         X[i], Y[j] = False, False
         return m[np.ix_(X, Y)]
    
mathfux
  • 5,759
  • 1
  • 14
  • 34