将矩阵的行乘以向量? [英] Multiply rows of matrix by vector?

查看:33
本文介绍了将矩阵的行乘以向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 25 列 23 行的数字 矩阵,以及一个长度为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆