Preallocating memory for a 3 dimensional array

Hi,
I am new to Julia.
I am writing a code where a 3 dimensional array, say A, each index with an initial size “chi”, is modified, and in the due course of time iteratively, (say 1000 times) the size of each index will grow gradually, from some “chi” to a bigger value “chi_max”.

Is there a way to preallocate memory for a 3 d array of size “chi_max” each at the start, so that there are no reallocations?
I think this would cause considerable speed up of the code.
Thanks,
Jay.

Yep! Depending on the type of data in the array there are some common functions. zeros([Int | Float64 | ...], chi_max, chi_max, chi_max) will give you a 3D array of zeros. Similarly, falses gives an array of Bool. They also have counterparts ones and trues.

For a more general array, and to save on initialising the values use

A = Array{TypeOfElement}(undef, chi_max, chi_max, chi_max)

where TypeOfElement is whatever type you want.

Hi,
Thanks for your quick reply.
Actually in my code I need to deal with a bunch of these kind of objects and there are a lot of tensor contractions involved which lead to increase in the size.

To begin with I would like to work with just (chi)^3 sized object rather than going over the whole (chi-max)^3 tensor as it leads to considerable improvement in the performance.

Is there no way to work with a (chi)^3 sized object but at the same time have a (chi_max)^3 space allocated for it where rewrites keep happening?

Views might be what you need?

julia> A = ones(4, 4)
4×4 Matrix{Float64}:
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0

julia> B = view(A, 1:2, 1:2)
2×2 view(::Matrix{Float64}, 1:2, 1:2) with eltype Float64:
 1.0  1.0
 1.0  1.0

julia> B * [1, 2] # B acts as 2x2 matrix
2-element Vector{Float64}:
 3.0
 3.0

julia> B[2, 2] = 9999 # But the underlying memory is shared with A
3

julia> A
4×4 Matrix{Float64}:
 1.0     1.0  1.0  1.0
 1.0  9999.0  1.0  1.0
 1.0     1.0  1.0  1.0
 1.0     1.0  1.0  1.0

You may also want to look at ResizableArrays, which may fit your use case.

Hi,
Thanks to both the quick replies.
Both view and resizeablearrays seem to do the job.

I had another related question.

Say I had an array c1t := (n * n * n * n). If I want to reshape it into something
(n^2 * n^2), then what would be the most efficient way to get this done in Julia?
Should I use something like

c1t_r = reshape(c1t, size(c1t, 1)*size(c1t, 2), size(c1t, 3)*size(c1t, 4)) 

or

c1t = reshape(c1t, size(c1t, 1)*size(c1t, 2), size(c1t, 3)*size(c1t, 4))

or wherever I want to use the rank 2 tensor, substitute

reshape(c1t, size(c1t, 1)*size(c1t, 2), size(c1t, 3)*size(c1t, 4))

or something else?
Thanks.