How to replace MATLAB cell array ({}) in Julia

This might be a very basic question. I have a MATLAB version iterative solver where I need to store my solution on each iteration. In MATLAB one can easily store by this sol{}. I was wondering what would be the equivalence cell structure in Julia?

I know Array could be one approach to store the solution but I am having a hard time to initialize the store variable inside the loop.

make an empty array and push! into it.

Thank you Oscar.

The direct equivalent of a cell array is a Vector{Any} in Julia (or Array{Any,N} for an N-dimensional cell array), i.e. an array which can hold any type of data. You can initialize this to an empty array with a = Any[] or just a = [], and then append values with push!(a, v).

However, to gain the full performance benefits of Julia one usually avoids abstractly typed containers, i.e. we usually try to give all our arrays concrete element types if we know the type of data in advance. For example, if you know that you want to store 1d arrays Vector{Float64} of floating-point data, you can do:

a = Vector{Float64}[]   # an empty container for Vector{Float64}
push!(a, x)  # store an array x in a

Better yet, you can try to write “type-generic” code where the element type of a is determined by the inputs to your computation. For example, in an iterative solver, you typically have an initial guess x0, and all subsequent iterations are of the same type. So in this case you can initialize a to hold arrays of the same type as x0:

a = typeof(x0)[]  # empty array to hold objects of the same type as x0

This gives you maximum flexibility/generality — e.g. you can run the same code with vectors of single-precision (Float32) or complex (Complex{Float64}) data, and it will work (and be fast) without modification. In the long run, one tries to get in the habit of writing type-generic Julia code. But to start with you can specialize everything for e.g. Vector{Float64} and go back and generalize it later.


Thank you Steven for your nice explanation.

This may also be of interest:

1 Like

I think that’s quite a different meaning of “cell array” what is meant in Matlab.