user1690124
user1690124

Reputation: 303

Matrix multiplication by row

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,]
  }
}

Upvotes: 0

Views: 151

Answers (1)

Andrey Shabalin
Andrey Shabalin

Reputation: 4614

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

Upvotes: 4

Related Questions