Helper Function: Build mxAlgebra object out of a string

I put this together for someone and thought I'd share it. It's a quick helper function for building an MxAlgebra object that takes a string instead of an expression as the first argument.
stringToMxAlgebra <- function(algString, name=NA, dimnames=NA) {
eval(substitute(mxAlgebra(tExp, name=name, dimnames=dimnames), list(tExp = parse(text=algString)[[1]])))
}
This is useful because it lets you use paste() and rep() to quickly and easily insert values from R variables into the string, then parse the string as an mxAlgebra argument. The use case this time was to include a matrix exponent (that is A %*% A %*% A %*% A...) with a variable exponent. With this function, the code goes:
stringToMxAlgebra(paste(rep("A", nReps), collapse = " %*% "), name="whatever")
Sublime! Saves a lot of
However, for matrix exponentiation in this example I would favor
\eval(A) %&% (\evec(A) %^% nReps)
which should turn about a bit more computationally efficient when nReps is not small.
Log in or register to post comments