# Struct Parameterized by One Dimension of StaticArray Matrix Members

I would like to preallocate some static arrays for use with DifferentialEquations.jl. My problem uses a lot of matrices that are 3 x N, where N is not known ahead of time. I would like to use StaticArrays.jl and do something like:

``````struct Memory{N}
f::MArray{Tuple{3,N},Float64,2,3N}
g::MArray{Tuple{3,N},Float64,2,3N}
...
end
``````

Unfortunately, 3N, the number of entries, does not work as N is not seen as an integer but a type. Is there a good way to do this?

I have done something similar once, and I opted for a vector os static arrays, something like:

``````struct A{T<:SMatrix...}
x_solute :: Vector{T}
end
``````

Depending on the way the operations on these vectors are performed the individual static elements do not need to be mutable at all, they can be replaced without cost.

But anyway you could just use

That will work well, I think.

1 Like

Ah, if I understand correctly, we drop the need to define 3 ahead of time, but only ever initialize with matrices of size 3 by N.

1 Like

Introduce an extra type parameter for `3*N`, and have an inner constructor calculate or verify it. Sketch for the first option:

``````struct Memory{N,M}
f::MArray{Tuple{3,N},Float64,2,M}
g::MArray{Tuple{3,N},Float64,2,M}
function Memory{N}(...) where N
M = 3 * N
...
end
end
``````
2 Likes

Thanks! I like this one a lot. It make sit easy to have other sizes too, like Vector{N}, etc. in the struct.

You might also be interested in https://github.com/mateuszbaran/HybridArrays.jl, which are static along some dimensions.

2 Likes

Can this have any performance benefit relative to simply parameterizing the complete type?

And what are the possible benefits, or not, of defining a large static arrays versus defining a large array of small static elements?

I don’t understand what the latter means.

That has no performance benefits and just exercises the compiler. See the StaticArrays.jl docs.

Oh, sorry. In general I meant to ask if there is any reason for a code run slower if dealing with a struct defined as

``````struct A{T}
x :: T
end
``````

relative to

``````struct A
x :: SArray{3,Float64}
end
``````

If the instances of the first are initialized with the same type as that of the second.

No.

1 Like