# How do I declare a matrix in a struct?

## How do I declare a matrix in a struct?

Contents

Problem Description:

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!

## Solution – 1

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

## Solution – 2

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])
``````
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.