pythonpython-3.xsympy

How to generate an n-dimensional matrix in SymPy?


How can I generate a matrix A with n rows and 2 columns in SymPy where n is a symbolic variable in Python?

import sympy
n = sympy.Symbol("n")
A = sympy.Matrix.zeros(n,2)

It went wrong.
TypeError: cannot determine truth value of Relational

I want to solve this problem and make it possible to generate a matrix like this.


Solution

  • To generate a matrix with a symbolic number of rows and/or columns you can use FunctionMatrix like this:

    from sympy import symbols, FunctionMatrix, Lambda
    i, j, m, n = symbols('i j m n', integer=True)
    A = FunctionMatrix(m, n,Lambda((i, j), 0))
    A[100,100]
    # Out: 
    # 0
    

    You can display the matrix

    display(A)
    FunctionMatrix(m, n, Lambda((i, j), 0))
    # Out:
    # FunctionMatrix(m, n, Lambda((i, j), 0))
    

    but of course if you try

    A.as_explicit()
    # Out:
    # . . .
    # ValueError: Matrix with symbolic shape cannot be represented explicitly.
    

    whereas with non-symbolic values for the numbers of rows/columns you can visualize the matrix:

    FunctionMatrix(3, 4, Lambda((i, j), 0)).as_explicit()
    # Out:
    #     Matrix([
    # [0, 0, 0, 0],
    # [0, 0, 0, 0],
    # [0, 0, 0, 0]])
    

    Something like Matrix.zeros won't help because symbols as numbers of rows/columns are not allowed:

    from sympy import Matrix, symbols
    m, n = symbols('m n', integer=True)
    
    A = Matrix.zeros(m, n) # ❌ gives an error if m,n are symbols
    # Out:
    # . . .
    # TypeError: cannot determine truth value of Relational
    
    m, n = 3, 4 # m and n are not symbols anymore
    A = Matrix.zeros(m, n) # ✅ this is ok