# Array with user-defined number of dimensions

**URL:** <https://discourse.julialang.org/t/array-with-user-defined-number-of-dimensions/16268>\
**Category:** General Usage\
**Created:** [October 13, 2018, 7:35am UTC](https://discourse.julialang.org/t/array-with-user-defined-number-of-dimensions/16268 "2018-10-13T07:35:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ferran\_Mazzanti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ferran_mazzanti/32/7458_2.png) [@Ferran\_Mazzanti](https://discourse.julialang.org/u/Ferran_Mazzanti)\
**Post date:** [October 13, 2018, 7:35am UTC](https://discourse.julialang.org/t/array-with-user-defined-number-of-dimensions/16268/1 "2018-10-13T07:35:51Z")

</div>

Hi folks,  
just a quick (and probably stupid) question. I need to define an array whose unmber of dimensions is given by the user. The user should provide an inpt integer n and, depending on its value the array must change. For exemple:  
if n=1 res = zeros(100)  
if n=2 res = zeros(100,100)  
if n=3 res = zeros(100,100,100)  
etc

Is there any simple way to do that (and then to Access the array elements) other tan using the if’s?  
Best regards and thanks,  
Ferran.

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [October 13, 2018, 7:55am UTC](https://discourse.julialang.org/t/array-with-user-defined-number-of-dimensions/16268/2 "2018-10-13T07:55:29Z")

</div>

This works:

```julia
julia> f(n::Int, ::Val{N}) where N = zeros(ntuple(i->n, Val(N))...);

julia> f(2, Val(1))
2-element Array{Float64,1}:
 0.0
 0.0

julia> f(2, Val(2))
2×2 Array{Float64,2}:
 0.0 0.0
 0.0 0.0

julia> f(2, Val(3))
2×2×2 Array{Float64,3}:
[:, :, 1] =
 0.0 0.0
 0.0 0.0

[:, :, 2] =
 0.0 0.0
 0.0 0.0

julia> @code_warntype f(2, Val(2))
Body::Array{Float64,2}
1 1 ─ %1 = $(Expr(:foreigncall, :(:jl_alloc_array_2d), Array{Float64,2}, svec(Any, Int64, Int64), :(:ccall), 3, Array{Float64,2}, :(n), :(n), :(n), :(n)))::Array{Float64,2}
  │ %2 = invoke Base.fill!(%1::Array{Float64,2}, 0.0::Float64)::Array{Float64,2} ││┃│ zeros
  └── return %2        

```
