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)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다