【问题标题】:Replacing values in the columns of a matrix according to a vector of indices?根据索引向量替换矩阵列中的值?
【发布时间】:2019-11-01 11:36:21
【问题描述】:

我有一个零矩阵:

M <- matrix(0, nrow = 10, ncol = 5)

和一个索引向量

V <- c(1,5,3,2,3,4,1,3,2,4)

我想将条目 M[i,V[i]] 替换为 1, i 在 1:10。如何在不使用蛮力(for循环)的情况下做到这一点?下面是使用蛮力的代码,这在更高维度上效率不高:

for(i in 1:10) M[i,V[i]] = 1

【问题讨论】:

    标签: r matrix vector


    【解决方案1】:

    您可以从向量 V 中创建一个矩阵并直接使用它,即

    M[matrix(c(seq_along(V), V), ncol = 2)] <- 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 2016-02-19
      • 2018-11-23
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多