【问题标题】:Optimizing all values in a matrix优化矩阵中的所有值
【发布时间】:2016-11-23 03:51:46
【问题描述】:

我正在尝试编写代码以基于优化有效地求解矩阵中的所有值。我试图找到使方程最小化的 x 值:

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

我写了一些代码来完成这个任务,但它并不漂亮(也不是很快)。

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
  }
}

我一直在努力想出让这件事更快的最佳方法。我在想也许将 apply 与一些自定义函数一起使用可能是路线,但我很难找到一个可行的解决方案。任何正确方向的指针将不胜感激。

【问题讨论】:

    标签: r matrix optimization


    【解决方案1】:

    试试这个:

    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))
    

    【讨论】:

    • 你也可以做类似apply(test_mat, 1:2, function(x) {optimize(f = mSS, lower = 0, upper = 3, a = x)$minimum})的事情(同样的推理,但是使用apply而不是sapplymatrix
    • @ZheyuanLi:确实,刚刚做了基准测试,sapply 更快
    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多