【发布时间】:2021-07-25 05:27:07
【问题描述】:
我有一个 MATLAB 代码,我正在尝试将其转换为 Python。我使用 eval() 在 MATLAB 中评估我的符号数组。但我找不到如何在 Python 中解决这个问题。这是一个简单的例子:
MATLAB 代码:
%values to be assigned
input = [10 20 30; ...
15 25 20; ...
20 20 10]
%decision variables
x_1_1 = input(1)
x_2_1 = input(2)
x_3_1 = input(3)
x_1_2 = input(4)
x_2_2 = input(5)
x_3_2 = input(6)
x_1_3 = input(7)
x_2_3 = input(8)
x_3_3 = input(9)
%symbolic arrray
symbolic_eq = sym('x_',[3,3])
%any math operation
m = [-1 0 0 ; ...
0 -1 0 ; ...
0 1 -1 ]
% new equations for symbolic array
multp_eq = m*symbolic_eq
% get results
results = eval(multp_eq)
Python 代码:
from sympy import *
import numpy as np
#values to be assigned
input = np.array([[10, 20, 30, 15, 25, 20, 20, 20, 10]])
#decision variables
x_1_1 = input[0]
x_2_1 = input[1]
x_3_1 = input[2]
x_1_2 = input[3]
x_2_2 = input[4]
x_3_2 = input[5]
x_1_3 = input[6]
x_2_3 = input[7]
x_3_3 = input[8]
#symbolic array (edited)
symbolic_eq = symarray('x', (4, 4))
symbolic_eq = np.array(symbolic_eq [1:, 1:])
#any math operation
m = np.array([[-1, 0, 0 ],
[ 0, -1, 0 ],
[ 0, 1, -1 ]])
#new equations for symbolic array
multp_eq = m*symbolic_eq
# get results
results = eval(multp_eq)
另外,对于 MATLAB 和 Python,如何轻松定义我的 input() 变量?
【问题讨论】:
-
symarray 的第一个索引是 0 而不是 1。
-
我修改了python symarray函数代码。我曾在我的代码中考虑过这种情况,但在这里忘记了。谢谢@Corralien
标签: python matlab eval sympy code-conversion