向矩阵的所有行添加一个向量 [英] add a vector to all rows of a matrix

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

问题描述

我正在最大化似然函数并试图减少循环.我想将向量(要估计的参数)添加到矩阵(数据)的所有行.向量的长度等于矩阵的列.a+b 会给出错误的结果,因为 R 的回收规则是按列而不是按行.

I am maximizing a likelihood function and trying to reduce the loop. I want to add the vector(parameters to be estimated) to all rows of a matrix (data). The length of vector equals to the column of matrix. a+b would give the wrong results because the recycle rule of R is by column not row.

a<-c(1,2,0,0,0)  # parameters to be optimized
b<-matrix(1,ncol=5,nrow=6) # data
t(a+t(b)) # my code would work, anything more intuitive?

期望输出

        [,1] [,2] [,3] [,4] [,5]
    [1,]    2    3    1    1    1
    [2,]    2    3    1    1    1
    [3,]    2    3    1    1    1
    [4,]    2    3    1    1    1
    [5,]    2    3    1    1    1
    [6,]    2    3    1    1    1

错误输出

a+b
    [,1] [,2] [,3] [,4] [,5]
[1,]    2    3    1    1    1
[2,]    3    1    1    1    2
[3,]    1    1    1    2    3
[4,]    1    1    2    3    1
[5,]    1    2    3    1    1
[6,]    2    3    1    1    1

推荐答案

我们可以使用col来复制'a'元素

We can use col to replicate the 'a' elements

b + a[col(b)]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    2    3    1    1    1
#[2,]    2    3    1    1    1
#[3,]    2    3    1    1    1
#[4,]    2    3    1    1    1
#[5,]    2    3    1    1    1
#[6,]    2    3    1    1    1

或者更快的选择是使用 rep

Or a faster option would be to use rep

b + rep(a, each = nrow(b))

<小时>

或者使用sweep

sweep(b, 2, a, "+")

基准

set.seed(24)
b <- matrix(sample(0:9, 8000*5000, replace=TRUE), ncol=5000)
a <- sample(0:3, 5000, replace=TRUE)
system.time(b + a[col(b)])
#  user  system elapsed 
#  1.08    0.06    1.14 
system.time(b + rep(a, each = nrow(b)))
#   user  system elapsed 
#   0.83    0.03    0.86 

system.time(t(a+t(b)))
#   user  system elapsed 
#   1.14    0.03    1.17 

system.time(sweep(b, 2, a, "+"))
#  user  system elapsed 
#  0.62    0.06    0.69 

这篇关于向矩阵的所有行添加一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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