# problems with product of vector of symbols with square matrix

Hi,

I am trying to do some experiments with symbols (variable vector) and multiplications with a coefficient matrix.

The code is the following:

A = matrix(QQ,[
[2,1,2,-6],
[-1,2,1,7],
[3,-1,-3,-1],
[1,5,6,0]
])

k = A.transpose().kernel()
basis = k.basis()
t = 'real'
var('x1')
assume(x1,t)
var('x2')
assume(x2,t)
var('x3')
assume(x3,t)
var('x4')
assume(x4,t)

x = vector([x1,x2,x3,x4])
print "x",x
xT = x.transpose()
print "xT",xT
print "A*x",A*x
print "xT*A",xT*A


with the following output:

x (x1, x2, x3, x4)
xT [x1]
[x2]
[x3]
[x4]
A*x (2*x1 + x2 + 2*x3 - 6*x4, -x1 + 2*x2 + x3 + 7*x4, 3*x1 - x2 - 3*x3 - x4, x1 + 5*x2 + 6*x3)
xT*A
Traceback (most recent call last):
File "", line 1, in <module>

File "/tmp/tmpuVBZ96/___code___.py", line 27, in <module>
exec compile(u'print "xT*A",xT*A
File "", line 1, in <module>

File "element.pyx", line 2751, in sage.structure.element.Matrix.__mul__ (sage/structure/element.c:19587)
File "coerce.pyx", line 856, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (sage/structure    /coerce.c:8169)
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 4 by 1 dense matrices over Symbolic Ring'     and 'Full MatrixSpace of 4 by 4 dense matrices over Rational Field'


As you can see, A*x was successful, but xT*A is giving an exception. Do you have any idea on why? How would you solve this?

edit retag close merge delete

Sort by » oldest newest most voted

First, you should notice that when you typed xT = x.transpose(), you got the following deprecation warning :

DeprecationWarning: The transpose() method for vectors has been deprecated, use column() instead
(or check to see if you have a vector when you really want a matrix)
See http://trac.sagemath.org/10541 for details.
exec(code_obj, self.user_global_ns, self.user_ns)


In particular, x.transpose() leads to a column matrix:

sage: x.transpose()
[x1]
[x2]
[x3]
[x4]


So it is OK if you multiply on the right, not on the left (which explains why xT*A did not work):

sage: A * (x.transpose())
[2*x1 + x2 + 2*x3 - 6*x4]
[ -x1 + 2*x2 + x3 + 7*x4]
[  3*x1 - x2 - 3*x3 - x4]
[       x1 + 5*x2 + 6*x3]


If you want to multiply on the left, you should use x.row():

sage: x.row()
[x1 x2 x3 x4]
sage: (x.row()) * A
[  2*x1 - x2 + 3*x3 + x4   x1 + 2*x2 - x3 + 5*x4 2*x1 + x2 - 3*x3 + 6*x4       -6*x1 + 7*x2 - x3]


That said, vectors are not matrices, they are vertical/horizontal agnostic and adapt themselves to the situation:

sage: A*x
(2*x1 + x2 + 2*x3 - 6*x4, -x1 + 2*x2 + x3 + 7*x4, 3*x1 - x2 - 3*x3 - x4, x1 + 5*x2 + 6*x3)
sage: x*A
(2*x1 - x2 + 3*x3 + x4, x1 + 2*x2 - x3 + 5*x4, 2*x1 + x2 - 3*x3 + 6*x4, -6*x1 + 7*x2 - x3)


which explains why A*x worked.

more