Python:使用任意元素计算矩阵?

时间:2017-04-08 11:23:26

标签: python linear-algebra

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

例如,我想说我想用元素创建方形矩阵:a,a,a,a并将其添加到方形矩阵中,其元素为:b,b,b,b。

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

其他例子,我将矩阵乘以标量k并想要矩阵内的k。如果我没有指定k的确切值,我将收到错误,但我希望它被任意估价并显示为" k"。

1 个答案:

答案 0 :(得分:1)

编辑:根据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}))