user1819274 - 8 months ago 62

R Question

I'm trying to write code to efficiently solve for all values in a matrix based on an optimization. I'm trying to find the value of x that minimizes the equation:

`(x - (1 / ((1 / x) - sqrt(1 / x))))^2`

I wrote some code that accomplishes this task, but it isn't pretty (nor is it fast).

`mSS <- function(x)`

{

#Sum of squares for X and the transformation

(x - (1 / ((1 / test_mat[rows, cols]) - sqrt(1 / x))))^2

}

n = 151

m = 50000

test_mat = matrix(rnorm(n * m, mean = 0, sd = 1), n, m)

trans_mat = matrix(data = NA, n, m)

#Go through each row/col position in array, find value that minimizes mSS function

for (cols in 1:ncol(test_mat)) {

for (rows in 1:nrow(test_mat)) {

trans_mat[rows, cols] = optimize(mSS, c(0, 3))$minimum

}

}

I'm mentally stuck trying to figure out the best approach for making this go faster. I was thinking maybe using apply with some custom functions might be the route, but I'm having difficulty figuring out a workable solution. Any pointers in the right direction would be appreciated.

Answer

Try this:

```
mSS<-function(x, a)
{
#Sum of squares for X and the transformation
(x-(1/((1/a)-sqrt(1/x))))^2
}
y <- as.numeric(test_mat)
ty <- sapply(y, function(x) optimize(mSS,c(0,3),a=x)$minimum)
trans_mat <- matrix(ty, nrow=nrow(test_mat))
```

Source (Stackoverflow)