0
votes

Is there any way to calculate matrix c faster?

a=matrix(runif(10),2,5)
b=matrix(runif(15),3,5)

c=matrix(,nrow(a)*nrow(b),5)
k=0
for(i in 1:nrow(a)){
  for(j in 1:nrow(b)){
    k=k+1
    c[k,]=a[i,]*b[j,]
  }
}
1
Why not just use R standard matrix multiplication? A %*% B If you want fast matrix multiplication you could use Strassen's algorithm: en.wikipedia.org/wiki/Strassen_algorithm - Spencer Wieczorek
a%*%b does not work because the dimension of c is 6 by 5. - user1690124

1 Answers

4
votes

Here is my version:

c1 =  a[ rep(1:nrow(a), each = nrow(b)), ] * 
      b[ rep(1:nrow(b), times = nrow(a)), ];
all.equal(c, c1);

> TRUE