Python-如何将矩阵与符号和 0 相乘 [英] Python-How to multiply matrix with symbols and 0s
问题描述
我是 python 的新手,但是有没有办法将矩阵与 0 和符号相乘?例如,见下文:
I am brand new to python, but is there any way to multiply matrices with both 0's and symbols? For example, see below:
import sympy as sym
import numpy as np
teams=np.matrix([[1,2],[3,4]])
teams=teams-1
n=4
x,a,b=sym.symbols('x a b')
X=np.empty((n,n), dtype=object)
Y=np.empty((n,n), dtype=object)
Z=np.empty((n,n), dtype=object)
for i in range(n):
for j in range(n):
if j==i:
X[i,j]=x
elif ([i,j] in teams.tolist()):
Y[i,j]=a
elif ([j,i] in teams.tolist()):
Y[i,j]=a
else:
Z[i,j]=b
for i in range(n):
for j in range(n):
if X[i,j]==None:
X[i,j]=0
if Y[i,j]==None:
Y[i,j]=0
if Z[i,j]==None:
Z[i,j]=0
print(np.matmul(X,Y))
TypeError Traceback (most recent call last)
<ipython-input-189-00b753462a2d> in <module>
2 print(Y)
3 print(Z)
----> 4 print(np.matmul(X,Y))
TypeError: ufunc 'matmul' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
我知道它为什么会搞砸,我正在尝试将一个符号乘以一个数字,但我想知道是否有任何方法可以让这个认识到符号乘以 0 只是零,如果被添加到,应该被忽略另一个符号.
I know why it is messing up, I am trying to multiply a symbol by a number, but I was wondering if there was anyway to make this recognize that a symbol times 0 is just zero and should be disregarded if being added to another symbol.
推荐答案
我用 print(np.dot(X,Y))
而不是 print(np.matmul) 测试了你的代码(X,Y))
并且它起作用了.根据文档 np.matmul
优于 np.dot
矩阵乘法,但我无法弄清楚如何使用 np 来做.矩阵
.我尝试了 np.matmul(X, Y, cast='unsafe')
,但结果是同样的错误.我不认为错误是由加 0 或乘以 0 引起的,sympy 能够进行简化.
I tested your code with print(np.dot(X,Y))
instead of print(np.matmul(X,Y))
and it worked. According to the documentation np.matmul
is preferred over np.dot
for matrix multiplication, but I wasn't able to figure out how to do it using np.matmul
. I tried np.matmul(X, Y, casting='unsafe')
, but the same error resulted. I don't think the error is caused by adding 0 or multiplying by 0, sympy is able to do simplifications.
例如
x = sym.symbols('x')
print(x + 0)
print(x*0)
print(3*x + 5*x)
按预期返回 x、0 和 x*8.
returns just as expected x, 0 and x*8.
希望这对您有所帮助.
这篇关于Python-如何将矩阵与符号和 0 相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!