Domanda

I have a N x K matrix in R, where each row is a observation and each column is a variable that has a fixed lower and upper bound.

My matrix is initially set with values between 0 and 1. What's the best way to de-normalize this matrix? I'm using the following function:

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)

The first variable ranges from -1 to 1, the second from -2 to 2, and so on... Another solution is:

   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
 }

Is there a simple (and faster) way to achieve this? Thanks!

EDIT: Results from the answers below:

Results from the answers below:

È stato utile?

Soluzione

You can use a double transpose:

t(lb + t(x) * (ub - lb))

Altri suggerimenti

Here's a solution using 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top