How to create vector of specific structure?

I have this structure:

julia> Base.@kwdef mutable struct Vsines
           instancename::String="Def"
           value::Float64=0.0
       end

and I want to create a vector of “Vsines” instances (name of this vector is “s”), in which I dont know initially the size of this vector, however, it grows in iterative manner when (event = true). So, I wrote something like below, but I have an error. Could you please correct my way?

julia> i=0; event = true;
julia> if event == true
          i +=1;
          s[i]=Vsines()
       end
ERROR: UndefVarError: s not defined
Stacktrace:
 [1] top-level scope
   @ REPL[3]:3
s=Vsines[]  #initialize
push!(s,Vsines())  # push new element
1 Like

Can we assign specific value meanwhile we using push? such as:

Base.@kwdef mutable struct Vsines
           instancename::String="Def"
           value::Float64=0.0
       end
s=Vsines[]
push!(s.value,Vsines(,0.0))

s is a vector of Vsines, it doesn’t have a field called value. Just push into s

1 Like
push!(s,Vsines("name",0.0))
1 Like

Thank you very much!

Thank you very much!!

Could you please let me know how to solve this problem?

ulia> Base.@kwdef mutable struct Vsines
           instancename::Array{String,3} = ["NN","NN","NN"]
           value::Array{Int128,3} = [0,0,0]
       end
Vsines

julia> s=Vsines[]
Vsines[]

julia> push!(s,Vsines())
ERROR: MethodError: no method matching Array{String, 3}(::Vector{String})
Closest candidates are:
  Array{T, N}(::AbstractArray{S, N}) where {T, N, S} at array.jl:540      
  Array{T, N}(::BitArray{N}) where {T, N} at bitarray.jl:494
  Array{T, N}(::Core.Compiler.BitArray{N}) where {T, N} at bitarray.jl:494
  ...
Stacktrace:
 [1] convert(#unused#::Type{Array{String, 3}}, a::Vector{String})
   @ Base .\array.jl:532
 [2] Vsines(instancename::Vector{String}, value::Vector{Int64})  
   @ Main .\REPL[2]:2
 [3] Vsines(; instancename::Vector{String}, value::Vector{Int64})
   @ Main .\util.jl:450
 [4] Vsines()
   @ Main .\util.jl:450
 [5] top-level scope
   @ REPL[4]:1

The 3 is the dimension of the array, not the number of elements. What you there is a Vector, or, equivalently, an array of dimension 1:

julia> Base.@kwdef mutable struct Vsines
                  instancename::Vector{String} = ["NN","NN","NN"]
                  value::Vector{Int128} = [0,0,0]
              end
Vsines

julia> s=Vsines[]
Vsines[]

julia> push!(s,Vsines())
1-element Vector{Vsines}:
 Vsines(["NN", "NN", "NN"], Int128[0, 0, 0])


2 Likes

Thank you very much for your experience and explanation!

1 Like