Search code examples
rmatrixinteraction

Interact each row of matrix with same row in another matrix


In R I have two matrices X and Z and I would like a matrix W such that the row (i) of W contains row (i) of X interacted with row (i) of Z.

W(i) = X(i1)Z(i1) ... X(iJ)Z(i1) ... X(i1)Z(iK) ... X(iJ)Z(iK) 

Here is an example in small scale doing what I want:

set.seed(1)
n <- 3
K <- 2
J <- 3
X <- matrix(rnorm(J*n),ncol=J)
Z <- matrix(rnorm(K*n),ncol=K)

W <- matrix(NA,nrow=n,ncol=K*J)

for (i in 1:n)
    {
    for (k in 1:K)
        {
        for (j in 1:J)
            {
                 W[i,j + J*(k-1)] <- X[i,j] * Z[i,k]
            }
        }
    }

Is there a clever way to do that?


Solution

  • I ended up doing

    X[,sort(rep(1:J,K))] * Z[,rep(1:K,J)]