using Random #for creating data
#define struct
mutable struct MyType
::String
x::Int64
y::Vector{Float64}
zend
#instantiate an example struct
= MyType("hello", 1, [1., 1.5, 104.1]) a
MyType("hello", 1, [1.0, 1.5, 104.1])
How to initialize a vector of structs in Julia
Here’s an example of how to initialize a vector of structs in Julia. It’s sometimes useful to coerce other data structures into vectors of structs to perform operations on them, and so this snippet provides a basic example of creating and populating a vector of a custom struct
using Random #for creating data
#define struct
mutable struct MyType
::String
x::Int64
y::Vector{Float64}
zend
#instantiate an example struct
= MyType("hello", 1, [1., 1.5, 104.1]) a
MyType("hello", 1, [1.0, 1.5, 104.1])
This isn’t strictly necessary, but it can be useful. This just creates a new instance of MyType with random values
function MyType()
MyType(randstring(10), rand(1:100), rand(Float64, 3))
end
= MyType() a
MyType("WAc1LBvkFm", 33, [0.3619946274985777, 0.858479824777187, 0.720193448993144])
= 100
n
#initialize an n-vector with 0 values
= Vector{MyType}(undef, n)
v
#populate the vector
for i ∈ eachindex(v)
= MyType()
v[i] end
we want v to be a vector of MyType
typeof(v)
Vector{MyType} (alias for Array{MyType, 1})
and we want each element to be MyType
typeof(v[1])
MyType
and let’s check the first element
1] v[
MyType("HmSiEUvtnk", 24, [0.22658234942156086, 0.5284152678374769, 0.48072129238569283])