1

I have data matrix (X) of the dimensions 5000x250 plus an extra parameter Y (Dim: 5000x1). The following loop gives me the desired results, but it takes forever to compute.

for (i in 1:ncol(X))
  for (j in 1:nrow(X))
   {
   X[j,i]=Y[j,1]^X[j,i]
   }

Is there any way to optimize this? If I didn't require the exponential, I'd use matrix multiplication. Thanks!

aciM
  • 89
  • 1
  • 1
  • 8

2 Answers2

3

Turn your column vector y into a matrix and use elementwise ^.

matrix(y, nrow=nrow(X), ncol=ncol(X)) ^ X

or

rep(y, times=ncol(X)) ^ X
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
1

You can use the vectorised ^ if you construct a matrix of y's of the correct size:

x <- matrix(1:9,3)
y <- matrix(1:3,ncol=1)

do.call(cbind,replicate(ncol(x),list(y)))^x
     [,1] [,2]  [,3]
[1,]    1    1     1
[2,]    4   32   256
[3,]   27  729 19683
James
  • 65,548
  • 14
  • 155
  • 193