1

I have the following simplified case which is actually a much bigger performance hotspot:

epsilon <- c(-3, -4)
str(epsilon)
num [1:2] -3 -4

Q <- matrix(c(2, 1, 0, 3, 1, 0), nrow=3, ncol=2)
str(Q)
num [1:3, 1:2] 2 1 0 3 1 0
Q
     [,1] [,2]
[1,]    2    3
[2,]    1    1
[3,]    0    0

This is the correct result I need but it requires double-transposition i.e. expensive for large Qs:

t(epsilon*t(Q))
     [,1] [,2]
[1,]   -6  -12
[2,]   -3   -4
[3,]    0    0

However if I simply do the following I get different results (i.e. the second row is flipped):

Q*epsilon
     [,1] [,2]
[1,]   -6  -12
[2,]   -4   -3
[3,]    0    0

Mathematically speaking (epsilon*Q^T)^T should be the same as Q*epsilon^T but that's not what I want (doing Q%*%epsilon it would generate a 3x1 result).

Is there a way to achieve this without double transposing the potentially very large Q?

SkyWalker
  • 13,729
  • 18
  • 91
  • 187

1 Answers1

1

It would be easier to replicate with either col providing the index of the columns of 'Q' so that both elements are of the same length

Q * epsilon[col(Q)]

Or use rep

Q * rep(epsilon, each = nrow(Q))

Or with sweep

sweep(Q, 2, epsilon, `*`)
akrun
  • 874,273
  • 37
  • 540
  • 662