Getting 1D Subsets of Multi dimensional arrays in julia

走远了吗. 提交于 2020-01-23 11:54:32

问题


I have a multi dimensional array in julia:

julia> ac.value
3x100x3 Array{Float64,3}:
[:, :, 1] =
 0.29238   0.0751815  0.00843636   …  -0.0143826   0.0403283  0.0225896
 0.263146  0.080687   0.000462262     -0.00635778  0.0307563  0.0379104
 0.992458  0.986423   0.980587         0.561173    0.55516    0.549105 

[:, :, 2] =
 0.362155  0.13406   0.0741124  …   0.0231614   0.0156455   0.0121797
 0.325581  0.11181   0.0447847      0.0098042   0.0193873   0.0146943
 0.914888  0.852297  0.796608      -0.0500265  -0.0551787  -0.0520171

[:, :, 3] =
 0.269976  0.108082   0.0441809  …  0.0249861  0.0128778   0.0168318 
 0.218475  0.0997567  0.0532782     0.0243412  0.00742072  0.00978782
 0.96878   0.947455   0.931407      0.0796884  0.0710757   0.0630705 

When I look at

julia> ac.value[1,:,1]
1x100 Array{Float64,2}:
 0.29238  0.0751815  0.00843636  …  -0.0143826  0.0403283  0.0225896

I get a 2 dimensional array, but when I look at

julia> ac.value[:,1,1]
3-element Array{Float64,1}:
 0.29238 
 0.263146
 0.992458

I get a one dimensional array. Why is this so and what can I do so that in the former case I get a one-dimensional array?


回答1:


A quick hack to get 1D arrays is to append [:] to your array references. E.g.,

julia> A = rand(Int,3,3,3)
3x3x3 Array{Int32,3}:
[:, :, 1] =
  1059011904  -1092196516  -2083742447
 -1232110963     46419394    599245389
   747779547   1800837260   -460798437

[:, :, 2] =
  -154984919  1641929284  1335793910
 -1575337246  1100743707   333491108
   231729201  1543773782   338937245

[:, :, 3] =
 -1812252712    374672056  -156561770
   317145782  -1941995702   747015018
   127966143   -102265949  1068453724

julia> A[:,1,1]
3-element Array{Int32,1}:
  1059011904
 -1232110963
   747779547

julia> A[:,1,1][:]
3-element Array{Int32,1}:
  1059011904
 -1232110963
   747779547

julia> A[1,:,1]
1x3 Array{Int32,2}:
 1059011904  -1092196516  -2083742447

julia> A[1,:,1][:]
3-element Array{Int32,1}:
  1059011904
 -1092196516
 -2083742447

julia> A[1,1,:]
1x1x3 Array{Int32,3}:
[:, :, 1] =
 1059011904

[:, :, 2] =
 -154984919

[:, :, 3] =
 -1812252712

julia> A[1,1,:][:]
3-element Array{Int32,1}:
  1059011904
  -154984919
 -1812252712

You may also be interested in the ArrayViews package which may be more efficient depending on what you want to implement.



来源:https://stackoverflow.com/questions/23957734/getting-1d-subsets-of-multi-dimensional-arrays-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!