Matrix multiplication by row

倾然丶 夕夏残阳落幕 提交于 2019-12-25 02:27:11

问题


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:


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


来源:https://stackoverflow.com/questions/24988345/matrix-multiplication-by-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!