isinstance and MatrixSymbol

39 views
Skip to first unread message

Lorenzo Monacelli

unread,
Mar 5, 2020, 6:30:24 AM3/5/20
to sympy
Dear all,
I would like to implement some basic manipulation with matrices that I need. 
The problem I'm facing is that I cannot figure out how to recognize correctly a MatrixSymbol:
from sympy.abc import i,j
A = sy.MatrixSymbol("A",3,3)
B = sy.MatrixSymbol("B",3,3)
C = sy.MatrixSymbol("C",3,3)

pippo = A[i,j].subs(A, B+C)
isinstance(pippo.args[0].args[0].func, sy.MatrixSymbol)  # False
isinstance(B.func, sy.MatrixSymbol) #True
Note, that  pippo.args[0].args[0] is B and if you print pippo.args[0].args[0].func it returns 
sympy.matrices.expressions.matexpr.MatrixSymbol

So why is it not working? How can I check if it is a matrix and stop the recursion?

Bests,
Lorenzo

Oscar Benjamin

unread,
Mar 5, 2020, 6:55:21 AM3/5/20
to sympy
On Thu, 5 Mar 2020 at 11:30, Lorenzo Monacelli
<lorenzo92...@gmail.com> wrote:
>
> Dear all,
> I would like to implement some basic manipulation with matrices that I need.
> The problem I'm facing is that I cannot figure out how to recognize correctly a MatrixSymbol:
> from sympy.abc import i,j
> A = sy.MatrixSymbol("A",3,3)
> B = sy.MatrixSymbol("B",3,3)
> C = sy.MatrixSymbol("C",3,3)
>
> pippo = A[i,j].subs(A, B+C)
> isinstance(pippo.args[0].args[0].func, sy.MatrixSymbol) # False
> isinstance(B.func, sy.MatrixSymbol) #True

The .func attribute gives MatrixSymbol so you could use:

pippo.args[0].args[0].func is sy.MatrixSymbol

or (note no .func):

isinstance(pippo.args[0].args[0], sy.MatrixSymbol)

> Note, that pippo.args[0].args[0] is B and if you print pippo.args[0].args[0].func it returns
> sympy.matrices.expressions.matexpr.MatrixSymbol
>
> So why is it not working?

Because you are asking if MatrixSymbol is an instance of itself:

In [11]: isinstance(MatrixSymbol, MatrixSymbol)
Out[11]: False

--
Oscar

S.Y. Lee

unread,
Mar 5, 2020, 8:00:42 AM3/5/20
to sympy
I think that this is a gotcha with Python.
Python already returns False when checking out isinstance(int, int).

And in general OOP theory, class and instance should be different.

If you want to compare the class by class, then comparing with == or issubclass should suffice.

Lorenzo Monacelli

unread,
Mar 5, 2020, 8:14:22 AM3/5/20
to sympy
Thank you very much!
Indeed, now it works!
Reply all
Reply to author
Forward
0 new messages