gpt4 book ai didi

r - 如何在不使用应用或循环的情况下每 n 列矩阵插入一列

转载 作者:行者123 更新时间:2023-12-01 13:49:49 26 4
gpt4 key购买 nike

假设我有一个矩阵

M = diag(6)

我想插入

d = rep(5,6)

每第 3 列,所以输出是

M
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 0 0 0 0 0
[2,] 0 1 0 0 0 0
[3,] 0 0 1 0 0 0
[4,] 0 0 0 1 0 0
[5,] 0 0 0 0 1 0
[6,] 0 0 0 0 0 1
> d
[1] 5 5 5 5 5 5

输出:

     [,1] [,2] [,3] [,4]  [,5]   [,6]  [,7]   [,8]
[1,] 1 0 0 5 0 0 0 5
[2,] 0 1 0 5 0 0 0 5
[3,] 0 0 1 5 0 0 0 5
[4,] 0 0 0 5 1 0 0 5
[5,] 0 0 0 5 0 1 0 5
[6,] 0 0 0 5 0 0 1 5

最佳答案

我们通过更多列创建另一个 5 ('m1') 的矩阵,创建列索引(使用 setdiffseq)用“M”替换“m1”中的值

n <- 3
m1 <- matrix(5, ncol=ncol(M)+ncol(M)/n, nrow=nrow(M))
m1[,setdiff(1:ncol(m1),seq(4, ncol(m1), by=4))] <- M
m1
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,] 1 0 0 5 0 0 0 5
#[2,] 0 1 0 5 0 0 0 5
#[3,] 0 0 1 5 0 0 0 5
#[4,] 0 0 0 5 1 0 0 5
#[5,] 0 0 0 5 0 1 0 5
#[6,] 0 0 0 5 0 0 1 5

编辑:

我想与其创建另一个巨大的矩阵,不如cbind 额外的列然后排序

n1 <- ncol(M)/n
M1 <- matrix(5, nrow=nrow(M), ncol=n1)
M2 <- cbind(M, M1)
n2 <- seq(4, ncol(M2), by=4)
M3 <- M2[,order(c(setdiff(seq_len(ncol(M2)), n2), n2))]
M3
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,] 1 0 0 5 0 0 0 5
#[2,] 0 1 0 5 0 0 0 5
#[3,] 0 0 1 5 0 0 0 5
#[4,] 0 0 0 5 1 0 0 5
#[5,] 0 0 0 5 0 1 0 5
#[6,] 0 0 0 5 0 0 1 5

基准

M <- diag(5000)
n <- 3
system.time({
n1 <- ncol(M)/n
M1 <- matrix(5, nrow=nrow(M), ncol=n1)
M2 <- cbind(M, M1)
n2 <- seq(n+1, ncol(M2), by=n+1)
M3 <- M2[,order(c(setdiff(seq_len(ncol(M2)), n2), n2))]
})
# user system elapsed
# 0.699 0.068 0.769

n <- 3
system.time({
m1 <- matrix(5, ncol=ncol(M)+ncol(M)/n, nrow=nrow(M))
m1[,setdiff(1:ncol(m1),seq(n+1, ncol(m1), by=n+1))] <- M
})
#user system elapsed
# 0.722 0.061 0.785

identical(m1, M3)
#[1] TRUE

关于r - 如何在不使用应用或循环的情况下每 n 列矩阵插入一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com