Python: 计算任意元素的矩阵?

Python: Computing matrices with arbitrary elements?

如何在 python 中创建和计算具有任意元素的矩阵的解?

例如,假设我要创建包含元素 a,a,a,a 的方阵,并将其添加到包含元素 b,b,b,b 的方阵。

对于新矩阵中的每个元素,结果应该是 a+b,作为字母。

其他示例,我将一个矩阵乘以标量 k,并希望 k 在矩阵内部。如果我没有指定 k 的确切值,我将收到一个错误,但我希望它被任意赋值并显示为 "k".

编辑:根据PM 2Ring, SymPy的建议可能是解决方案。

其他答案:

我认为 TensorFlow 在这种情况下可能会对您有所帮助。

不过,在这种情况下,编写方程式可能会略有不同。

import tensorflow as tf

# define your variables before hand.
# tf.placeholder(<type of element>, <dimensions>)
arr1 = tf.placeholder(tf.float32, [2,2])
arr2 = tf.placeholder(tf.float32, [2,2])

# if it doesn't have dimension no need to mention.
scalar = tf.placeholder(tf.float32)

# these are your arrays which contain those arbitrary values you mentioned
multiplied_array = arr1*scalar
added_array = arr1+arr2
adding_to_multiplied = multiplied_array+arr1

# to evaluate these into any number, you need a session
sess = tf.Session()

# just provide values of arr1, scalar, arr2 to evaluate the results
print(sess.run(multiplied_array,{arr1:[[1,2],[3,4]],scalar:22}))
print(sess.run(added_array,{arr1:[[1,2],[3,4]],arr2:[[5,6],[7,8]]}))
print(sess.run(adding_to_multiplied,{arr1:[[1,2],[3,4]],arr2:[[5,6],[7,8]],scalar:22}))