gpt4 book ai didi

r - 如何在使用cbind循环R中创建一个空矩阵

转载 作者:行者123 更新时间:2023-12-02 01:06:14 25 4
gpt4 key购买 nike

我想为 R 中的每个步骤生成 cbind 矩阵,如何在 matlab 中创建一个初始空矩阵说 result=[] 然后为每次迭代 cbind?

最佳答案

在循环中使用cbind 非常慢。如果您事先知道大小,则可以预先分配矩阵并在循环中填充列。否则,使用 list。创建一个空列表并在循环中将向量添加到列表中。然后,在循环结束后将列表 cbind 成一个矩阵。

时间:

Preallocate matrix:
user system elapsed
1.024 0.064 1.084

Grow matrix with cbind:
user system elapsed
76.036 50.146 125.840

Preallocate list:
user system elapsed
0.788 0.040 0.823

Grow list by indexing:
user system elapsed
0.821 0.043 0.859

代码:

# Preallocate matrix.
f1 = function(x) {
set.seed(2718)
mat = matrix(ncol=x, nrow=x)
for (i in 1:x) {
mat[, i] = rnorm(x)
}
return(mat)
}

# Grow matrix with cbind.
f2 = function(x) {
set.seed(2718)
mat = c()
for (i in 1:x) {
mat = cbind(mat, rnorm(x))
}
return(mat)
}

# Preallocate list.
f3 = function(x) {
set.seed(2718)
lst = vector("list", length=x)
for (i in 1:x) {
lst[[i]] = rnorm(x)
}
res = do.call(cbind, lst)
return(res)
}

# Grow list by indexing.
f4 = function(x) {
set.seed(2718)
lst = list()
for (i in 1:x) {
lst[[i]] = rnorm(x)
}
res = do.call(cbind, lst)
return(res)
}

x = 3000

system.time(r1 <- f1(x))
system.time(r2 <- f2(x))
system.time(r3 <- f3(x))
system.time(r4 <- f4(x))

all.equal(r1, r2)
all.equal(r1, r3)
all.equal(r1, r4)

关于r - 如何在使用cbind循环R中创建一个空矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22316260/

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