Matrix multiplication algorithm

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

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的话,你可以尝试以下代码:

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

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

  1. > set.seed(0)
  2. > (a <- matrix(runif(12), 3))
  3. [,1] [,2] [,3] [,4]
  4. [1,] 0.8966972 0.5728534 0.8983897 0.62911404
  5. [2,] 0.2655087 0.9082078 0.9446753 0.06178627
  6. [3,] 0.3721239 0.2016819 0.6607978 0.20597457
  7. > (b <- matrix(rnorm(8), 4))
  8. [,1] [,2]
  9. [1,] -0.928567035 0.7635935
  10. [2,] -0.294720447 -0.7990092
  11. [3,] -0.005767173 -1.1476570
  12. [4,] 2.404653389 -0.2894616

我们有:

  1. > a %*% b
  2. [,1] [,2]
  3. [1,] 0.50614499 -0.9861506
  4. [2,] -0.37108354 -1.6249737
  5. [3,] 0.08650475 -0.6949853
  6. > matrix(
  7. colSums(t(a)[, rep(1:nrow(a), each = ncol(b))] * b[, rep(1:ncol(b), nrow(a))]),
  8. nrow(a),
  9. byrow = TRUE
  10. )
  11. [,1] [,2]
  12. [1,] 0.50614499 -0.9861506
  13. [2,] -0.37108354 -1.6249737
  14. [3,] 0.08650475 -0.6949853

希望这对你有帮助。

英文:

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

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

Example: Given two matrices a and b like below

  1. &gt; set.seed(0)
  2. &gt; (a &lt;- matrix(runif(12), 3))
  3. [,1] [,2] [,3] [,4]
  4. [1,] 0.8966972 0.5728534 0.8983897 0.62911404
  5. [2,] 0.2655087 0.9082078 0.9446753 0.06178627
  6. [3,] 0.3721239 0.2016819 0.6607978 0.20597457
  7. &gt; (b &lt;- matrix(rnorm(8), 4))
  8. [,1] [,2]
  9. [1,] -0.928567035 0.7635935
  10. [2,] -0.294720447 -0.7990092
  11. [3,] -0.005767173 -1.1476570
  12. [4,] 2.404653389 -0.2894616

we have

  1. &gt; a %*% b
  2. [,1] [,2]
  3. [1,] 0.50614499 -0.9861506
  4. [2,] -0.37108354 -1.6249737
  5. [3,] 0.08650475 -0.6949853
  6. &gt; matrix(
  7. + colSums(t(a)[, rep(1:nrow(a), each = ncol(b))] * b[, rep(1:ncol(b), nrow(a))]),
  8. + nrow(a),
  9. + byrow = TRUE
  10. + )
  11. [,1] [,2]
  12. [1,] 0.50614499 -0.9861506
  13. [2,] -0.37108354 -1.6249737
  14. [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:

确定