# [R] Row-wise kronecker product with Matrix package

ilai keren at math.montana.edu
Thu Feb 9 18:37:29 CET 2012

```Maybe one of these will improve:
>help.search('kronecker')
...
spam::kronecker         Kronecker Products on Sparse Matrices
spam::spam.class        Class "spam"
base::kronecker         Kronecker Products on Arrays
Matrix::kronecker-methods
Methods for Function 'kronecker()' in Package
'Matrix'

I doubt it because they will calculate the "full" Kronecker prod and
it will be up to you to index the rows, but you never know...

system.time(A[, rep(seq(ncol(A)), each = ncol(B))] *
B[,rep(seq(ncol(B)),ncol(A))])
user  system elapsed
0.016   0.000   0.019
> system.time(kronecker(A,B)[c(1,4),])
user  system elapsed
0.008   0.000   0.008
> system.time(spam::kronecker(A,B)[c(1,4),])
user  system elapsed
0.008   0.000   0.009

Cheers

On Thu, Feb 9, 2012 at 9:38 AM, Ally <a.rushworth at stats.gla.ac.uk> wrote:
>
> I'm trying to calculate the row-wise kronecker product A \Box B of two
> sparse matrices A and B, and am struggling to find a quick way to do this
> that takes advantage of sparseness.  I thought a good idea would be to use
> "rep" to construct 2 matrices of the same dimension of the end product, and
> multiply these two together:
>
> library(Matrix)
> A<-Matrix(c(1,0,0,0,0,1,2,0), 2, 4)
> B<-Matrix(c(2,5,0,0,0,1,0,0,0,0), 2, 5)
>
> A[, rep(seq(ncol(A)), each = ncol(B))] * B[, rep(seq(ncol(B)),ncol(A))]
>
> This works, but for much larger problems is slow (compared to keeping A and
> B dense).  I was wondering why this happens, and whether there might be a
> way around it?
>
>
> Alastair
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Row-wise-kronecker-product-with-Matrix-package-tp4373437p4373437.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help