How to define structure with its field is matrix?

I have a structure as below:

struct R
    value::Vector{Float64} = []
end

however, I want to make the “value” to be matrix (undefined,3) with elements type as “Float64” so I adjusted as below:

struct R
    value::Array{Vector{Float64}, 3} = []
end

So later, I can push value such as

push!(R.value, [5;6;7])

but it didnt work, any idea?

this is not an Array{Vector{Float64}, 3}, this is a Vector{Any}, which is just an alias for Array{Any, 1}. So the important thing is that this has dimension equals 1, instead of 3.

1 Like

Also, you can’t push to a 3-dimensional array, only a 1-dimensional one. You could use a vector of vectors (Vector{Vector{Float64}}) and push to it just fine. If all of your entries are length 3, you might also want to look into StaticArrays.jl.
If you specifically want a Matrix (which is an alias for Array{T, 2}), and you also need it to be resize-able, you could try ElasticArrays.jl.

I used as suggested but I got error.

julia> Base.@kwdef mutable struct R
           value::Vector{Vector{Float64}} = []
       end
R

julia> push!(R.value, [5;6;7])
ERROR: type DataType has no field value
Stacktrace:
 [1] getproperty(x::Type, f::Symbol)
   @ Base .\Base.jl:28
 [2] top-level scope
   @ REPL[1]:1

R is the name of the struct, not an instance of it. It’s like saying x = Int + 1 (that doesn’t make sense).
try

r = R()
push!(r, [1,2,3])
1 Like

Yes, I missed creating an instance first.
Thank you very much!

1 Like

You may want to do this:

struct R
    value::Vector{Vector{Float64}}
end

R() = R(Vector{Vector{Float64}}(undef,0))

x = R()
push!(x.value, [5;6;7])
1 Like

The below is growing vertically, although the input data are ([9;9;9] and [1;1;1])is as seen below:

julia> Base.@kwdef mutable struct R
                         value::Vector{Vector{Float64}} = []
                     end
R

julia> r = R()
R(Vector{Float64}[])

julia> push!(r.value, [9;9;9])
1-element Vector{Vector{Float64}}:
 [9.0, 9.0, 9.0]

julia> push!(r.value, [1;1;1])
2-element Vector{Vector{Float64}}:
 [9.0, 9.0, 9.0]
 [1.0, 1.0, 1.0]

Is there any way to make it grow horizontally, i.e., similar to below:

 [9.0 1.0]
 [9.0 1.0]
 [9.0 1.0]

No. Not with a vector-of-vectors anyway. See if ElasticArrays is what you want.

1 Like