3
votes

NOTE: I am not referring to matrix multiplication as in here - not even with the twist of the transposed discussed on the other post.


I have these two matrices...

Matrix A:

A <- matrix(c(1,1,1,-1,1,1,1,-1,1,-1,-1,1), ncol=4)
       [,1]    [,2]     [,3]     [,4]  
[1,]    1       -1        1        -1       
[2,]    1        1       -1        -1     
[3,]    1        1        1         1     

...and matrix B:

B <- matrix(c(1,2,3,2,1,3,2,3,1), ncol=3)
       [,1]    [,2]     [,3] 
[1,]    1        2        2 
[2,]    2        1        3 
[3,]    3        3        1 

I want to get with [R] code:

       [,1]    [,2]    [,3] 
[1,]    1*1     1*2     1*2 
[2,]    1*2     1*1     1*3
[3,]    1*3     1*3     1*1 

       [,1]    [,2]    [,3] 
[1,]   -1*1    -1*2    -1*2 
[2,]    1*2     1*1     1*3
[3,]    1*3     1*3     1*1 

       [,1]    [,2]    [,3] 
[1,]    1*1     1*2     1*2 
[2,]   -1*2    -1*1    -1*3
[3,]    1*3     1*3     1*1 

       [,1]    [,2]    [,3] 
[1,]   -1*1    -1*2    -1*2 
[2,]   -1*2    -1*1    -1*3
[3,]    1*3     1*3     1*1 

It's not linear algebraic multiplication because there is no sum at the end of the multiplications. It's not a Kronecker product. I have tried with apply(A, 2, function(x) A * B but it doesn't work, because although I can specify that I want the columns of A one at a time, I don't know how to do the same for the columns of B.

I am not set on any particular type of object (list, matrix, array) as the output.

The question is: How can I multiply element-wise and column-wise these two matrices to end up with either another matrix or a "list" object or array?

3

3 Answers

7
votes

You can try something like the following:

> lapply(as.data.frame(A), `*`, B)
$V1
     [,1] [,2] [,3]
[1,]    1    2    2
[2,]    2    1    3
[3,]    3    3    1

$V2
     [,1] [,2] [,3]
[1,]   -1   -2   -2
[2,]    2    1    3
[3,]    3    3    1

$V3
     [,1] [,2] [,3]
[1,]    1    2    2
[2,]   -2   -1   -3
[3,]    3    3    1

$V4
     [,1] [,2] [,3]
[1,]   -1   -2   -2
[2,]   -2   -1   -3
[3,]    3    3    1

Regarding your follow up question in the comments below, if your end aim is for the column sums of each of these sub-matrices, you can achieve this with:

> lapply(as.data.frame(A), function(x) colSums(x * B))
$V1
[1] 6 6 6

$V2
[1] 4 2 2

$V3
[1] 2 4 0

$V4
[1]  0  0 -4
4
votes

Not sure if you want an array or a list at the end. If an array, you can use apply with some reshaping

array(apply(A, 2, function(x) x*B), c(3,3,4))
# OR array(apply(A, 2, `*`, B), c(3,3,4))
1
votes
A <- matrix(c(1,1,1, -1,1,1, 1,-1,1, -1,-1,1), 3)
B <- matrix(c(1,2,3, 2,1,3, 2,3,1), 3)

C <- array(NA, c(3,3,4))
for(i in 1:4) C[,,i] <- B*A[,i]