Search code examples
pythonnumpysymbolic-math

Abstract matrix multiplication with variables


I know about the ability of python to do matrix multiplications. Unfortunately I don't know how to do this abstractly? So not with definite numbers but with variables.

Example:

M = ( 1   0 ) * ( 1   d )
    ( a   c )   ( 0   1 )

Is there some way to define a,c and d, so that the matrix multiplication gives me

( 1   d       )
( a   a*d + c )

?


Solution

  • Using sympy you can do this:

    >>> from sympy import *
    >>> var('a c d A B')
    (a, c, d, A, B)
    >>> A = Matrix([[1, 0], [a, c]])
    >>> A
    Matrix([
    [1, 0],
    [a, c]])
    >>> B = Matrix([[1, d], [0, 1]])
    >>> B
    Matrix([
    [1, d],
    [0, 1]])
    >>> M = A.multiply(B)
    >>> M
    Matrix([
    [1,       d],
    [a, a*d + c]])