将矩阵的行乘以矢量? [英] Multiply rows of matrix by vector?
本文介绍了将矩阵的行乘以矢量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个25列23行的数字matrix
和一个长度为25的向量.如何在不使用for
循环的情况下将矩阵的每一行与向量相乘?
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?
结果应该是25x23的矩阵(与输入大小相同),但是每一行都已乘以向量.
The result should be a 25x23 matrix (the same size as the input), but each row has been multiplied by the vector.
从@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
推荐答案
我认为您正在寻找sweep()
.
# Create example data and vector
mat <- 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
vec <- 1:5
# Use sweep to apply the vector with the multiply (`*`) function
# across columns (See ?apply for an explanation of MARGIN)
sweep(mat, MARGIN=2, vec, `*`)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 4 6 8 10
[3,] 3 6 9 12 15
这是R的核心功能之一,尽管多年来对其进行了改进.
It's been one of R's core functions, though improvements have been made on it over the years.
这篇关于将矩阵的行乘以矢量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文