Save memory of a translational symmetric matrix

I have a mult-dimension matrix (or perhaps tensor more appropriately), for example:
a = rand(5, 5, 5, 5). It satisfies translational symmetry, i.e. a[i, j, k, l] = a[i - k, j, l].
In such case, how could I save the memory for constructing this? I would use it for some tensor contraction. Thank you!

You could create a custom <: AbstractArray type that calculates the required elements on demand, just storing a single one from each equivalence class. Just implement the Array interface (link is to latest, if you are using v0.6 change accordingly).


Following your suggestion, I am trying something like this:

struct TransSymmetric{T, N} <: AbstractArray{T, N}
    data::AbstractArray{T, N-1}
    dims::NTuple{N, Int}

Since the underlying data is one dim less than what it appears, I intend to try N-1 in the type parameters, which is wrong, however. Then I tried:

struct TT1{T, N} <: AbstractArray{T, N}
    data::AbstractArray{T, typeof(TT1).parameters[2]-1}
    dims::NTuple{N, Int}

This shows that BoundsError: attempt to access svec(). I assume the struct hasn’t been initiated before accessing its type parameters? My question is how can I restrict the dim of data inside?

This isn’t something you can do, unfortunately. For a workaround, see templates - Expressions depending on integer type parameters in type definitions in Julia are not allowed - Stack Overflow and Arithmetic on integer type parameters


Use two independent type parameters, and have an inner constructor check them.

1 Like