Selecting submatrix within functions

5 posts / 0 new
Offline
Joined: 10/08/2009 - 22:37
Selecting submatrix within functions

I am writing some functions that need to select some submatrices with variable indices. Let's consider the following sample code. The issue is that mxModel() only recognizes x in the gobal environment rather than inside a function. Have I missed something? Thanks.

myFun <- function() {
x <- 2
cat("Matrix in R:\n")
A1 <- matrix(1:16, ncol=4, nrow=4)
B1 <- A1[1:x,1:x, drop=FALSE]
print(B1)
myModel <- mxModel("test",
A2 <- mxMatrix("Full", nrow=4, ncol=4, values=1:16, name="A2"),
B2 <- mxAlgebra(A2[1:x, 1:x], name="B2"))
cat("Matrix in mxModel:\n")
print(mxEval(B2, mxRun(myModel, silent=TRUE)))
}
myFun()

x <- 3
myFun()

sessionInfo()

#

#

#

#

[1] tools_2.15.2

Offline
Joined: 07/31/2009 - 15:14
eval(parse(...

Hi Mike

I think I got around this type of problem with the following:

for (k in 1:nItems) {
elementCovString <- paste("mxAlgebra(expression=expectedCovariances[",k,",",k,"], name='itemCovariances')")
elementCov <- eval(parse(text=elementCovString))
...

YMMV of course (not sure if it will work for you), but perhaps this will help.

Offline
Joined: 10/08/2009 - 22:37
Thanks Michael and Ralf. I

Thanks Michael and Ralf.

I will use eval(parse()) for the time being.

Offline
Joined: 05/26/2010 - 09:44
Simple solution

I think the simplest solution would be to define x in the global environment, this can be done inside the function by using
x <<- 2
Otherwise there are possibilities to use, as Mike pointed out, paste and eval functions. Timothy Brick wrote about this in a previous thread: http://openmx.psyc.virginia.edu/thread/1096

Offline
Joined: 07/31/2009 - 15:24
Another way to do it is: B2

Another way to do it is:

B2 <- eval(substitute(mxAlgebra(A2[1:val, 1:val], name="B2"), list(val = x)))