1

I have the following code for some symbolic calculations:

from sympy import *
import numpy
A = MatrixSymbol('A',2,2)
f = Matrix(A).det() # for example only, the actual function is of the same flavor

How do I substitute A with an explicit Matrix of the same dimensions? I tried the following code but it doesn't produce desired result:

f.subs(A,Matrix(numpy.random.rand(2,2)))

Returned:

Matrix([
[ 0.204259256795002, 0.198427966386296],
[0.0929675373783559, 0.516653291115676]])[0, 0]*Matrix([
[ 0.204259256795002, 0.198427966386296],
[0.0929675373783559, 0.516653291115676]])[1, 1] - Matrix([
[ 0.204259256795002, 0.198427966386296],
[0.0929675373783559, 0.516653291115676]])[0, 1]*Matrix([
[ 0.204259256795002, 0.198427966386296],
[0.0929675373783559, 0.516653291115676]])[1, 0]
lingxiao
  • 1,214
  • 17
  • 33
  • This might interest you: [SymPy - substitute sybolic entries in a matrix](http://stackoverflow.com/questions/23208838/sympy-substitute-sybolic-entries-in-a-matrix); [How to substitute symbol for matrix using symPy and numPy](http://stackoverflow.com/questions/16904924/how-to-substitute-symbol-for-matrix-using-sympy-and-numpy); and https://github.com/sympy/sympy/issues/2962 – agold Oct 06 '15 at 15:09

1 Answers1

0

The substitution worked. It remained unevaluated by default. To evaluate it, use doit(), like

>>> f.subs(A,Matrix(numpy.random.rand(2,2))).doit()
-0.0866313884475072
asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • Sorry but `doit()` doesn't seem to evaluate the expression in my environment – lingxiao Oct 08 '15 at 01:24
  • Python 3.5.0 (default, Sep 27 2015, 12:06:50) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from sympy import * >>> import numpy >>> A = MatrixSymbol('A',2,2) >>> f = Matrix(A).det() >>> f.subs(A,Matrix(numpy.random.rand(2,2))).doit() Matrix([ [0.231174234097573, 0.828920556066121], [0.354529006116848, 0.323184714163859]])[0, 0]*Matrix([ [0.231174234097573, 0.828920556066121],... – lingxiao Oct 08 '15 at 01:36
  • >>> print(sympy.__version__) 0.7.6.1 – lingxiao Oct 08 '15 at 01:41
  • Ah, it seems this is a bug that is only fixed in the development version of SymPy. – asmeurer Oct 09 '15 at 22:59