Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column Wise [R] Matrix Multiplication

Tags:

r

matrix

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?

like image 588
Antoni Parellada Avatar asked Nov 30 '25 05:11

Antoni Parellada


1 Answers

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
like image 91
A5C1D2H2I1M1N2O1R2T1 Avatar answered Dec 01 '25 20:12

A5C1D2H2I1M1N2O1R2T1