Matrix multiplication algorithm

huangapple go评论68阅读模式
英文:

Algorithm for matrix multiplication

问题

我需要编写一个单循环算法来进行矩阵乘法,不使用%*%,而是利用colSums()来完成。

我已经尝试过研究矩阵乘法的特性,但未能找到可以使用colSums()实现的模式。

英文:

I am required to write a one-loop algorithm for matrix multiplication without using %*%, with the help of colSums().

I have tried working through matrix multiplication traits, but failed to find a pattern which can be attained with colSums().

答案1

得分: 1

如果你不允许使用%*%,而必须使用colSums的话,你可以尝试以下代码:

matrix(
    colSums(t(a)[, rep(1:nrow(a), each = ncol(b))] * b[, rep(1:ncol(b), nrow(a))]), 
    nrow(a),
    byrow = TRUE
)

示例:给定两个如下的矩阵ab

> set.seed(0)

> (a <- matrix(runif(12), 3))
          [,1]      [,2]      [,3]       [,4]
[1,] 0.8966972 0.5728534 0.8983897 0.62911404
[2,] 0.2655087 0.9082078 0.9446753 0.06178627
[3,] 0.3721239 0.2016819 0.6607978 0.20597457

> (b <- matrix(rnorm(8), 4))
             [,1]       [,2]
[1,] -0.928567035  0.7635935
[2,] -0.294720447 -0.7990092
[3,] -0.005767173 -1.1476570
[4,]  2.404653389 -0.2894616

我们有:

> a %*% b
            [,1]       [,2]
[1,]  0.50614499 -0.9861506
[2,] -0.37108354 -1.6249737
[3,]  0.08650475 -0.6949853

> matrix(
    colSums(t(a)[, rep(1:nrow(a), each = ncol(b))] * b[, rep(1:ncol(b), nrow(a))]), 
    nrow(a),
    byrow = TRUE
)
            [,1]       [,2]
[1,]  0.50614499 -0.9861506
[2,] -0.37108354 -1.6249737
[3,]  0.08650475 -0.6949853

希望这对你有帮助。

英文:

If you are NOT ALLOWED to use %*% and HAVE TO take colSums anyway, you can try

matrix(
    colSums(t(a)[, rep(1:nrow(a), each = ncol(b))] * b[, rep(1:ncol(b), nrow(a))]), 
    nrow(a),
    byrow = TRUE
)

Example: Given two matrices a and b like below

&gt; set.seed(0)

&gt; (a &lt;- matrix(runif(12), 3))
          [,1]      [,2]      [,3]       [,4]
[1,] 0.8966972 0.5728534 0.8983897 0.62911404
[2,] 0.2655087 0.9082078 0.9446753 0.06178627
[3,] 0.3721239 0.2016819 0.6607978 0.20597457

&gt; (b &lt;- matrix(rnorm(8), 4))
             [,1]       [,2]
[1,] -0.928567035  0.7635935
[2,] -0.294720447 -0.7990092
[3,] -0.005767173 -1.1476570
[4,]  2.404653389 -0.2894616

we have

&gt; a %*% b
            [,1]       [,2]
[1,]  0.50614499 -0.9861506
[2,] -0.37108354 -1.6249737
[3,]  0.08650475 -0.6949853

&gt; matrix(
+     colSums(t(a)[, rep(1:nrow(a), each = ncol(b))] * b[, rep(1:ncol(b), nrow(a))]),
+     nrow(a),
+     byrow = TRUE
+ )
            [,1]       [,2]
[1,]  0.50614499 -0.9861506
[2,] -0.37108354 -1.6249737
[3,]  0.08650475 -0.6949853

huangapple
  • 本文由 发表于 2023年6月15日 05:38:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定