Creating looping matrixes (Torus-like) with type inheritance

Context :

I am trying to create a cellular automata and want its behaviour on edges to be looping (ex : neighbour of the cell at [0,0] are the cells at [0,end] and [end, 0] (as well as [0,1] and [1,0] )
Some kind of torus-representing matrix (when 2d).

My hypothesis

Maybe a deformation from python OOP, but I thought that creating a subclass of Matrix that would have special properties such as Matrix[0] = Matrix[end] etc… would be the easiest approach

This way, if I ever intended to generalise it to a 3x3 or nxn Matrix, it would not change so much in the code because i would just be able to say Matrix[ ... , coord-1] to loop back
And similarly if i wanted to extend my reach, I could do Matrix[coord - k] and go as far as I want from the end, looping.

I’ve looked at several posts on Inheritance etc but it seems like Julia isn’t built for this type of programming, so here are my questions :

  • Is it worth trying to find a way to create this struct ?
  • What’s the better way to code this behaviour and make the code reusable as much as possible

I don’t mind installing Packages but I’d like to keep my code as simple as possible, I’ve seen the Class.jl package that might offer what I’m looking for but I’m not sure about it.

Note : I know that, in my case, I could do a borders check and filter values to make them modulo the matrix size but that doesn’t seem neither aesthetic nor very functional. Tell me if I’m wrong

Sure, this is something that is very natural to write in julia. There’s a few implementations of it kicking around, but it might be informative for you to try implementing it yourself.

Here’s some documentation on julia’s Abstract Array interface: Interfaces · The Julia Language

You just need to make a struct that wraps another Array, and then intercepts getindex and setindex! calls, and transforms the indices to match your desired boundary conditions.

1 Like

This type of thing has been discussed before, but I usually advocate “ghost cells” (periodic padding) rather than paying the price of wrapping indices on every array access. See e.g. Arrays with periodic boundaries - #4 by stevengj