Multi-dimensional type declaration within a mutable structure


#1

I’m new to Julia and I face the following issue. I try to declare a mutable structure like this:
“”"
mutable struct mystructname
X::Array{Float64}(4, 4)
end
“”"

But the compiler does not like it:

TypeError: mystructname: in type definition, expected Type, got Array{Float64,2}
include_string(::String, ::String) at loading.jl:522
include_string(::String, ::String, ::Int64) at eval.jl:30
include_string(::Module, ::String, ::String, ::Int64, ::Vararg{Int64,N} where N) at eval.jl:34
(::Atom.##102#107{String,Int64,String})() at eval.jl:82
withpath(::Atom.##102#107{String,Int64,String}, ::String) at utils.jl:30
withpath(::Function, ::String) at eval.jl:38
hideprompt(::Atom.##101#106{String,Int64,String}) at repl.jl:67
macro expansion at eval.jl:80 [inlined]
(::Atom.##100#105{Dict{String,Any}})() at task.jl:80

Any ideas?


#2

This should work:

mutable struct MyStructName
X::Array{Float64,2}
end

The difference is that Array{Float64,2} is a type whereas Array{Float64}(4,4) is an instance of that type. (Also, please quote your code with back-ticks `, triple for multiline code.)

Edit: also note that types are usually in CamelCase.


#3

Thanks a lot!

I’ve tried that, but if I understand correctly X::Array{Float64,2} is for any 2-dimensional array, so I need to specify somewhere else in the structure that I only allow (5,5) elements, something like:

mutable struct mystructname
X::Array{Float64,2}
i,j = size(X)
    if i != 5 || j != 5
        error
    end
end

Does that make sense?


#4

Have a read through the constructors-section in the docs. In particular this section and its example: https://docs.julialang.org/en/stable/manual/constructors/#Inner-Constructor-Methods-1


#5

If you know the size of your array you should use

If you still want to use array, you need to add your check in the constructor:

mutable struct mystructname
X::Array{Float64,2}
mystructname(x) = (size(x)!=(5,5)) ? error("invalid size") : new(x)
end