Abstract matrix multiplication with variables
Asked Answered
S

2

12

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 )

?

Starvation answered 20/10, 2017 at 12:33 Comment(1)
Have a look at sympy, a python library for symbolic computing.Kerch
E
19

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]])
Elasticize answered 20/10, 2017 at 15:5 Comment(0)
S
-1

Just like any variable, an array/matrix can only be initialized with specific values. The only thing you can do is make functions to make initialization easier

import numpy as np

def helper(a, c, d):
    A = np.array([[1, 0], [a, c]])
    B = np.array([[1, d], [0, 1]])
    return A @ B

(where the @ operator is explicit matrix multiplication operator)

Stratocumulus answered 20/10, 2017 at 12:44 Comment(2)
Should there be a function name?Flexure
@Asterisk: yes, of course, it's a normal function. fixed the typo.Stratocumulus

© 2022 - 2024 — McMap. All rights reserved.