Error with arrays in Python

1

I am trying to obtain the determinant of a matrix with the help of numpy.linalg.det (matrix) this is the code:

from sympy import *
#from numpy import *
import numpy as np
from matplotlib import *
from py_expression_eval import *
import matplotlib.pyplot as plt
#[1,2] es una fila
#[3,4] otra fila
M = [[1,2], [3,4]]
def matrixDet(matrix):
    return np.linalg.det(matrix)
M2 = input("Ingrese la matriz de la forma [1, 2] (esto es una fila), [3, 2] (esto es otra fila)")
print(matrixDet(M2))

the method works if I pass the matrix M but when passing it the matrix M2 does not recognize it even if it passes the same [[1,2], [3,4]]

I get the error:

Traceback (most recent call last):
  File "F:/Calculadoras Metodos/matrices/matrixDeterminante.py", line 13, in <module>
    print(matrixDet(M2))
  File "F:/Calculadoras Metodos/matrices/matrixDeterminante.py", line 11, in matrixDet
    return np.linalg.det(matrix)
  File "C:\Users\DanielPortatil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\linalg\linalg.py", line 1817, in det
    _assertRankAtLeast2(a)
  File "C:\Users\DanielPortatil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\linalg\linalg.py", line 202, in _assertRankAtLeast2
    'at least two-dimensional' % len(a.shape))
numpy.linalg.linalg.LinAlgError: 0-dimensional array given. Array must be at least two-dimensional
    
asked by Daniel V 06.05.2017 в 17:58
source

2 answers

1

The problem is that you are not passing a matrix but a string of text, if you want to enter the matrix the way you do you need to parse the input string and pass it to a list of lists or a bidimensional array of Numpy.

  • Entry of the form "[1,2][3,4]" :

    One option is to use split next to regular expressions to build the array from the string.

    import numpy as np
    import re
    
    
    def matrixDet(matrix):
        return np.linalg.det(matrix)
    
    def parse_matriz(cadena):
        # Entrada: una cadena del tipo '[a,b,c][d,f,e]...'
        # Salida una lista de la forma [[a,b,c],[d,e,f]] contruida con los datos de entrada
        cadena = cadena.replace(" ", "")
        return [[float(n) for n in row.split(',')]
                              for row in re.findall("\[(.*?)\]", cadena)]
    
    M2 = input("Ingrese la matriz de la forma [1,2] (esto es una fila), [3,2] (esto es otra fila)")
    M2=parse_matriz(M2)
    print('El determinante es:', matrixDet(M2))
    

    Starting from the fact that the user enters a string of the form '[1,2][3,4]' that may or may not contain spaces, the first thing is to eliminate them with replace(" ", "") . Done this with re.findall("\[(.*?)\]", cadena) we get a list with the rows of the matrix using the brackets as separators: ['1,2', '3,4'] .

    Now we just have to go through each chain of the previous list and separate the numbers using the comma, we pass them to float and put them into a list.

.

  • Entry of the form "[[1,2],[3,4]]" :

    Being a string that is valid python code, we can use eval() to pass it directly to a list. However, using eval() for unfiltered user entries is very dangerous and should never be used. What we can use is the secure version ast.literal_eval() :

    import numpy as np
    import ast
    
    
    def matrixDet(matrix):
        return np.linalg.det(matrix)
    
    M2 = ast.literal_eval(input("Ingrese la matriz de la forma [[1,2],[3,4]]: "))
    
    print('El determinante es:', matrixDet(M2))
    

.

Both forms admit spaces between the elements of the matrix and both allow entering both integers and floats. That is, for the first case is valid both [1,2][3,4] as [ 1,2] [3, 4] , same as for the second form.

In both cases it would be appropriate to validate the user's input to avoid exceptions.

    
answered by 06.05.2017 / 18:46
source
1

Hello to solve this use numpy.matrix () the code stayed like this:

from sympy import *
#from numpy import *
import numpy as np
from matplotlib import *
from py_expression_eval import *
import matplotlib.pyplot as plt
#[1,2] es una fila
#[3,4] otra fila
M = np.matrix('1 2; 3 4')
def matrizDet(matriz):
    matriz = np.matrix(matriz)
    return np.linalg.det(matriz)
M2 = input("Ingrese la matriz de la forma [1, 2] (esto es una fila), [3, 2] (esto es otra fila)")
print(matrizDet(M2))

Now if you read me the data that the user enters but the user must enter them like this: 1, 2; 3, 2 Anyway, if someone knows a way to work with the other way, I appreciate it.

    
answered by 06.05.2017 в 18:20