2

我在 R 中有一个 N x K 矩阵,其中每一行是一个观察值,每一列是一个具有固定下限和上限的变量。

我的矩阵最初设置为 0 到 1 之间的值。反规范化此矩阵的最佳方法是什么?我正在使用以下功能:

denormalizeMult = function(m, lb, ub)
{
 nobs = nrow(m)
 nvars = ncol(m)
 lbDiag = diag(lb, ncol = nvars)
 rangeM = diag(ub - lb, ncol = nvars) 

 m%*%rangeM + matrix(rep(lb, nobs), nrow = nobs, byrow = TRUE)
}

 # Example:
 # 3 variables, 9 observations
 x = matrix(runif(3*9), ncol = 3)

 # to denormalize a variable xi, just do lb[i] + (ub[i] - lb[i])*xi
 # ranges for each variable
 lb = c(-1,-2,-3)
 ub = c(1,2,3)

第一个变量的范围是 -1 到 1,第二个变量的范围是 -2 到 2,依此类推……另一个解决方案是:

   denormalize2 = function(population)
   {
     r = nrow(population)
     c = ncol(population)
     decm = matrix(rep(0, r*c), r, c)

     for(i in 1:r)
           decm[i,] = lb + (ub - lb) * population[i,]       
     decm
 }

有没有一种简单(更快)的方法来实现这一点?谢谢!

编辑:来自以下答案的结果:

以下答案的结果:

4

2 回答 2

1

这是使用的解决方案sweep()

## Example data
x <- matrix(c(0,0.5,1), nrow=3, ncol=3)  # A better example for testing 
lb = c(-1,-2,-3)
ub = c(1,2,3)

sweep(sweep(x, 2, ub-lb, FUN="*"), 2, lb, FUN="+")
#      [,1] [,2] [,3]
# [1,]   -1   -2   -3
# [2,]    0    0    0
# [3,]    1    2    3
于 2012-07-08T05:22:52.150 回答
1

您可以使用双重转置:

t(lb + t(x) * (ub - lb))
于 2012-07-08T05:28:23.880 回答