![](/img/trans.png)
[英]What is the most efficient way to convert 3D array into array of 2D arrays in Julia?
[英]What is the most efficient way to write each element of a 3D array consecutively to file?
我有一個大型3D陣列,我想將其作為單列寫入文件。 數據需要先按Z(從高到低)變化,然后按x(從低到高)變化,然后按y(從低到高)變化。 目前,我正在這樣做:
arr <<- array(0,dim=c(x,y,z)) # values aren't really 0
dataf <- data.frame(Px=rep(0,x*y*z))
ticker <- 0
for (j in 1:y){
for (i in 1:x){
for (k in z:1){
ticker <- ticker +1
dataf[ticker,1] <- arr[i,j,k]
}
}
}
write.table(dataf,file=filename,row.names=F,col.names=F)
這個過程很慢,並且似乎隨着迭代的進行而變慢(用進度條看到)。 我敢肯定有一種使用adply的方法,但我無法使其正常工作。 我像這樣切換z數據的順序:
for (n in 1:z)
arr_inv[,,n] <- arr[,,(z-n+1)]
然后嘗試這樣寫:
write.table(adply(arr,.margins=c(1,2,3))[4],file=filename,row.names=F,col.names=F)
我似乎沒什么快的,所以我想知道您是否知道該如何處理? 謝謝
一種(卷積)的方法是使用lapply
將數組在第三個維度上拆分為列表元素,然后使用mapply
重塑矩陣,最后將其轉換為輸出向量:
mat <- array( rep(1:9,each=3) , dim = c(3,3,3) )
mat
, , 1
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 3
[3,] 1 2 3
, , 2
[,1] [,2] [,3]
[1,] 4 5 6
[2,] 4 5 6
[3,] 4 5 6
, , 3
[,1] [,2] [,3]
[1,] 7 8 9
[2,] 7 8 9
[3,] 7 8 9
as.vector( t( mapply( c , lapply( 1:3 , function(x) as.vector( t(mat[,,x]) ) ) ) ) )
[1] 1 4 7 2 5 8 3 6 9 1 4 7 2 5 8 3 6 9 1 4 7 2 5 8 3 6 9
另外,下次請提供可復制的示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.