英文:
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
)
示例:给定两个如下的矩阵a
和b
:
> 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
> 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
we have
> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论