将矩阵的行乘以向量?
我有一个 25 列和 23 行的数字矩阵,以及一个长度为 25 的向量。如何在不使用 for
循环的情况下将矩阵的每一行乘以向量?
结果应该是一个 25x23 矩阵(与输入大小相同),但每一行都已乘以向量。
从@hatmatrix的答案中添加了可重现的示例:
matrix <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
vector <- 1:5
所需的输出:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 4 6 8 10
[3,] 3 6 9 12 15
I have a numeric matrix
with 25 columns and 23 rows, and a vector of length 25. How can I multiply each row of the matrix by the vector without using a for
loop?
The result should be a 25x23 matrix (the same size as the input), but each row has been multiplied by the vector.
Added reproducible example from @hatmatrix's answer:
matrix <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
vector <- 1:5
Desired output:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 4 6 8 10
[3,] 3 6 9 12 15
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为您正在寻找
sweep()
。它一直是 R 的核心功能之一,尽管多年来对其进行了改进。
I think you're looking for
sweep()
.It's been one of R's core functions, though improvements have been made on it over the years.
您可以使用:
或:
You could use either:
or:
实际上,
sweep
并不是我计算机上最快的选项:这会产生:
除了是最慢的选项之外,第二个选项还达到了内存限制 (2046 MB)。然而,考虑到剩下的选项,在我看来,双重换位似乎比扫描要好得多。
编辑
只是重复尝试较小的数据:
Actually,
sweep
is not the fastest option on my computer:This yields:
On top of being the slowest option, the second option reaches the memory limit (2046 MB). However, considering the remaining options, the double transposition seems a lot better than
sweep
in my opinion.Edit
Just trying smaller data a repeated number of times:
为了速度,可以在相乘之前从向量创建矩阵
For speed one may create matrix from the vector before multiplying
如果您想要速度,可以使用
Rfast::eachrow
。这是所有中最快的...If you want speed, you can use
Rfast::eachrow
. It is the fastest from all...这是另一个选项:
这适用于任何运算,而不仅仅是乘法。
Here is another option:
This works for any operation, not just multiplication.