我想在R中象征性地添加两个矩阵P和Q.我使用" rSymPai"库函数。然后我怎样才能找到等于P + Q的X.
/authorize
答案 0 :(得分:0)
包裹' rSymPy'只是Python的SymPy包的包装器。 This is the documentation for matrices
您需要Python / SymPy中的以下代码(使用SymPy live尝试):
P = Matrix([['P1','P2'],['P3','P4']])
Q = Matrix([['Q1','Q2'],['Q3','Q4']])
Result = P + Q
在R中,rSymPy函数sympy(...)
将Python代码作为字符串,因此您希望在R中生成以下字符串:
"P = Matrix([['P1','P2'],['P3','P4']])"
"Q = Matrix([['Q1','Q2'],['Q3','Q4']])"
您可以通过R字符串操作从问题中的变量P
和Q
生成此字符串。之后,您应该能够将它们与R sympy
函数一起使用(无法测试最后三行,因为我没有在此机器上安装Python和SymPy)
library(rSymPy)
# Copied from Question
P<-matrix(nrow=2, ncol=2)
for (i in 1:2){
for (j in 1:2) {
P[i,j] = paste0("P", i, j)
}
}
P
## [,1] [,2]
## [1,] "P11" "P12"
## [2,] "P21" "P22"
Q<-matrix(nrow=2, ncol=2)
for (i in 1:2){
for (j in 1:2) {
Q[i,j] = paste0("Q", i, j)
}
}
Q
## [,1] [,2]
## [1,] "Q11" "Q12"
## [2,] "Q21" "Q22"
# -----------------------------------
makeSymPyMatrix <- function(name, mat){
dim <- dim(mat) # needed to restore matrix dimensions
# Add the single quotes
mat <- Q
mat <- sub('(.*)',"'\\1'",mat)
# Add the inner commas
mat <- apply(mat, 1, function(row){paste(row, collapse = ',')})
# Add the inner brackets
mat <- sub('(.*)',"[\\1]",mat)
# Add the outer commas
mat <- paste(mat, collapse = ',')
# Add the outer brackets
mat <- sub('(.*)',"[\\1]",mat)
# Add the Matrix function
mat <- sub('(.*)',"Matrix(\\1)",mat)
return(mat)
}
# See what this function returns
makeSymPyMatrix(P)
## "Matrix([['P11','P12'],['P21','P22']])"
Pvar <- sympy(makeSymPyMatrix(P))
Qvar <- sympy(makeSymPyMatrix(Q))
Pvar + Qvar