ben_afobe ben_afobe - 1 year ago 73
Python Question

How can one suppress evaluation while still being able to index?

I have two small but very complicated matrices that I want to multiply. I've done this using sympy:


This gives me a MatMul object which saves a huge amount of time, and I'm not interested in a symbolic expression anyway, rather I want to evaluate at specific points later on.

If this was the end of my calculation it would be fine, but I then need to use elements of C in order to define a new equation, however, I cannot index it. I get the following,

In [286]: C[0]
Traceback (most recent call last):

File "<ipython-input-286-829e2440bf19>", line 1, in <module>

File "C:\Anaconda3\lib\site-packages\sympy\matrices\expressions\", line 242, in __getitem__
raise IndexError("Single index only supported for "

IndexError: Single index only supported for non-symbolic matrix shapes.

Is it possible to somehow index such an object? For example, in maple I can use a semi-colon which suppresses the output, while retaining information about the structure of the resulting object so I can index it.

Answer Source

You can index elements of C, e.g. C[0,0]. So this will give you the first row as a list:

row0 = [C[0, k] for k in range(C.shape[1])]

Here's an example. x and y are sympy symbols.

In [40]: A
[2*x + 1, x + 3],
[     -2,     3]])

In [41]: B
[-3,   3],
[ y, 2*y]])

In [42]: C = sympy.MatMul(A, B, hold=True)

In [43]: C[0,0]
Out[43]: -6*x + y*(x + 3) - 3

In [44]: [C[0,k] for k in range(C.shape[1])]
Out[44]: [-6*x + y*(x + 3) - 3, 6*x + 2*y*(x + 3) + 3]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download