I am failing to appropriately work with a Symbolic Matrix in R, with both rSymPy and Ryacas. In Matlab this is easy. I am looking for suggestions how to do this in R and get a similar output as in Matlab. To do this in Matlab I need the 'Symbolic Toolbox'.
In this example I wish to generate a Symbolic transition probability matrix "P", which is say 5 x 5, and has elements P11, P12,..., P55. I then want to use this matrix for multiplication (with itself and other matrices) and potentially perform also other operations.
(1) Matlab - Generate Symbolic Matrix -> OK
P = sym('P%d%d', [5 5])
(1) R - Get Symbolic Matrix -> OK
library(rSymPy)
P<-matrix(nrow=5, ncol=5)
for (i in 1:5){
for (j in 1:5) {
P[i,j]<-paste0(Sym("P"), i, j) # tried Var("P") also
}
}
then I want to mulitply these matrices.
(2) Matlab - Multiply Symbolic Matrix -> OK
P*P
works just fine.
(2) R - Multiply Symbolic Matrix -> Problem
sympy("P * P")
Need Help Here!
does not work. Many other attempts did not work either. I need suggestions on how to do this correctly and get the same output as, for example, in (2) Matlab.
Additional Task:
(3) Matlab - sym() each element separately -> OK
Moreover I would ask for a suggestion how to Sym() a single element of the matrix P in R as in Matlab.
for i = 1:5;
for j = 1:5;
P = sprintf('P%d%d',i,j);
assignin('caller',P,sym(P));
end;
end;
(3) R - Sym() each element separately -> Problem
Need Help Here!
Thx for all suggestions!
When I did this recently, I ended up writing a function to convert R matrices to the format required for Python (see the 2x2 matrix given in the example on page 3 of https://cran.r-project.org/web/packages/rSymPy/rSymPy.pdf).
Let's first start with defining the matrix
P
in R:I have just taken your code and adjusted it slightly. Specifically, for each element of the matrix
P
, create a SymPy variable for this element by doingVar(paste0("P", i, j))
. For example, wheni = j = 1
, we will be creating the Sympy variableP11
. The output ofVar
is the string"P11"
which we store inP[1,1]
.At this time, we have defined an R matrix
P
whereP
is given by:We have created a
SymPy
variable for each element ofP
, but we haven't defined the symbolic matrix as yet. This is our next step.We define the function to convert the R matrix to Python's format:
You use the above function as follows to define the symbolic matrix
P
:(I am just using
cat(..., "\n")
to print the matrix nicely in R).Finally, compute
P*P
as follows:And this works with
rSymPy
: