我是个新手,我想打印符号矩阵的轨迹,并用函数ccode生成C代码
目前,我有以下信息:
import sympy as sp
# Creates a symbolic matrix (3x3) with symbol A
A = sp.MatrixSymbol('A', 3, 3)
# Trace of a matrix
traceM=sp.Trace(A)
# Generate C code
print(sp.ccode(traceM))如果我打印(sp.pprint)矩阵A,我将得到:
In [49]:sp.pprint(sp.Matrix(A))
如果我打印A的轨迹,则会出现以下错误
In [50]:sp.pprint(sp.Matrix(traceM))
TypeError:
Data type not understood; expecting list of lists or lists of values.我在跳着想要

。
此外,如果我尝试从跟踪生成C代码,我将得到以下消息
In [51]: print(sp.ccode(traceM))
// Not supported in C:
// Trace
Trace(A)我一直在想:
A[0, 0]+A[1, 1]+A[2, 2]有人能帮我一把吗?
注意:如果我使用numpy函数(traceM=numpy.trace(A)),它会给出预期的结果……但我应该也能得到同样的结果...
诚挚的问候,
发布于 2020-12-04 23:56:02
因此,我认为这里的目标是展开该跟踪表达式,并将其替换为显式求和。我发现执行展开过程的唯一方法是通过使用rewrite (我被暗示这是因为Trace类有一个名为_eval_rewrite_as_Sum的方法)。
用于生成C源代码的模块是codegen module (也请参阅Aaron Meurer的codegen教程及其github repo)。
这是在SymPy 1.7上测试的
import sympy as sp
from sympy.utilities.codegen import codegen
N=3
A = sp.MatrixSymbol('A', N, N)
traceM = sp.Trace(A).rewrite(sp.Sum)
[(c_name, c_code), (h_name, c_header)] = codegen(("f", traceM), "C89", "test", header=False, empty=False)
print(c_code)结果是这样的:
#include "test.h"
#include <math.h>
double f(double *A) {
double f_result;
f_result = A[0] + A[4] + A[8];
return f_result;
}需要注意的一件事是,2D数组A is accessed as a 1-dimensional array。
https://stackoverflow.com/questions/65097927
复制相似问题