How do I declare a matrix in a struct?
Asked Answered
C

2

11

In my code

mutable struct frame
    Lx::Float64
    Ly::Float64
    T::Matrix{Float64}  #I think the error is here

    function frame(
        Lx::Float64,
        Ly::Float64,
        T::Matrix{Float64}
    )
        return new(Lx, Ly, T)
    end
end

frames = frame[]
push!(frames, frame(1.0, 1.0, undef)) #ERROR here I try nothing, undef, any
push!(frames, frame(2.0, 1.0, undef)) #ERROR here I try nothing, undef, any

frames[1].T = [1 1 2]
frames[2].T = [[2 4 5 6] [7 6 1 8]]

I got the following error in ::Matrix

ERROR: MethodError: no method matching frame(::Float64, ::Float64, ::UndefInitializer)
Closest candidates are:
  frame(::Float64, ::Float64, ::Matrix) 

I need to define the dimensionless matrix inside the structure and then pass the matrices with different dimensions, but I'm having an error when I push!

Cullet answered 6/12, 2022 at 15:31 Comment(0)
T
5

You want frame(1.0, 1.0, Matrix{Float64}(undef, 0, 0))

Taverner answered 6/12, 2022 at 15:35 Comment(0)
C
8

The error is because there is no method for the types you call:

julia> methods(frame)
# 1 method for type constructor:
 [1] frame(Lx::Float64, Ly::Float64, T::Matrix{Float64})

julia> typeof(undef)
UndefInitializer

It is possible to make mutable structs with undefined fields, by calling new with fewer arguments:

julia> mutable struct Frame2
           Lx::Float64
           Ly::Float64
           T::Matrix{Float64} 
           Frame2(x,y) = new(x,y)
           Frame2(x,y,z) = new(x,y,z)
       end

julia> a = Frame2(1,2)
Frame2(1.0, 2.0, #undef)

julia> b = Frame2(3,4,[5 6])
Frame2(3.0, 4.0, [5.0 6.0])

julia> a.T = b.T;

julia> a
Frame2(1.0, 2.0, [5.0 6.0])
Chirpy answered 6/12, 2022 at 15:39 Comment(0)
T
5

You want frame(1.0, 1.0, Matrix{Float64}(undef, 0, 0))

Taverner answered 6/12, 2022 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.