You are here

Helper Function: Build mxAlgebra object out of a string

2 posts / 0 new
Last post
tbrick's picture
Joined: 07/31/2009 - 15:10
Helper Function: Build mxAlgebra object out of a string

Hey, all.

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")
neale's picture
Joined: 07/31/2009 - 15:14
Sublime! Saves a lot of

Sublime! Saves a lot of faffing about trying to do exactly that kind of thing.

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