如何初始化多维数组以在不同文件中的同一变量上使用Julia的ncread()?

时间:2017-10-24 22:20:29

标签: arrays multidimensional-array julia netcdf

我在Julia 0.5.0中使用NetCDF包从~10个不同的netcdf文件中读取相同的多维变量。有没有更好的方法来循环文件并将它们合并到一个总体的多维数组中,而不是创建像我现在一样的数组数组?

目前,我的代码设置如下:

files = ["file1", "file2", "file3", ... , "file10"] 
#length(files) = 10

var = Array{Array}(10)

for i in collect(1:1:10)
    var[i] = ncread(files[i], "x")
end

其中

size(var) = 10

size(var[1]) = (192,59,193) #from file1
.
.
.
size(var[10]) = (192,59,193) #from file10

哪个有效,但不是所需的格式,因为我后来想要在当前子数组中沿着Dimension Y取平均值。理想情况下,我想使用ncread()x读入一个多维数组var,这样大小就像

size(var) = (10,192,59,193)

,其中

var[1,:,:,:] #from file1
.
.
.
var[10,:,:,:] #from file10

我认为可能需要hcat()push!(),但我不确定如何在for-loop之前初始化多维数组以考虑ncread()输出?我必须对文件中的~8个变量执行此操作,并且在调用ncread()之前我不知道不同变量的维度或长度。

2 个答案:

答案 0 :(得分:3)

filenames = ["file$i" for i = 1:10]; # make some filenames
ncread(filename) = rand(2,3,4) # define a dummy function similar to yours

a = ncread(filenames[1]) # read the first file to get the size
output = Array{Float64}(length(filenames),size(a)...); #preallocate the full array, lookup splatting to see how this works
output[1,:,:,:] = a # assign the data we already read
for i in 2:length(filenames) # read and assign the rest
    output[i,:,:,:] = ncread(filenames[i])
end

答案 1 :(得分:2)

NCO使用ncecat

ncecat in*.nc out.nc

然而,如此少的代码做这么多可能会导致你的头爆炸。