Creating a struct containing "derived variables"

I am using a struct to hold parameters of a model. For example, let’s say I have two parameters sigma and mu. It is convenient to also store some variables that are functions of these parameters in the same struct. For example, I may create a grid that can be calculated as a function of sigma and mu. So, I have the struct storing

struct mytype
    sigma::Float64
    mu::Float64
    grid::Array{Float64}
end

What I want to do, is to create an object of type mytype, giving it values for sigma and alpha, with the element grid then created automatically by a function that I would define. Is this possible?

Sure, you only need to define a constructor:

julia> struct A
           sigma::Float64
           computed::Vector{Float64}
       end

julia> function A(sigma)
           computed = [ sigma*i for i in 1:10 ]
           return A(sigma, computed)
       end
A

julia> A(0.1)
A(0.1, [0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9, 1.0])

(note that Array{Float64} is an abstract type, you probably want Array{Float64,1}, which is the same as Vector{Float64})

3 Likes

(Or define any function that returns your struct, for that matter. A constructor is just a conveniently named function for a “standard” way to form your struct, especially if you need to enforce some requirement that must be true of your struct fields, but if there are multiple different ways you might want produce your struct then you might want multiple different function names.)

4 Likes

You may also want to take a look at the not-so-well-known Base.@kwdef macro