How to loop over vector with varying inner-dimensions?

Hello!

Suppose I have:

Values = SVector{3, Int64}[[3, 0, 1], [2, 3, 4], [3, 4, 3], [2, 3, 2], [0, 2, 2], [4, 2, 4], [4, 2, 4], [0, 3, 3], [4, 2, 0], [2, 2, 0], [0, 0, 0], [0, 0, 2], [2, 1, 4], [2, 0, 4], [1, 2, 2], [1, 1, 0], [0, 1, 2], [1, 3, 4], [1, 4, 4], [4, 0, 1]]

Which a Vector of SVectors with a dimension of 3. I can loop over this as such:

for (i,j,k) in Values
# do something
end

Suppose now I have:

Values = SVector{2, Int64}[[3, 0], [2, 3], [3, 4], [2, 3], [0, 2], [4, 2], [4, 2], [0, 3], [4, 2], [2, 2], [0, 0], [0, 0], [2, 1], [2, 0,], [1, 2], [1, 1], [0, 1], [1, 3], [1, 4], [4, 0]]

Now looping with the previous loop, with (i,j,k) will fail. I know I can change it to (i,j). My question is instead;

Is there an elegant way to avoid switching amount of indices by a “manual” decision and instead let code handle it?

Other than “if dim = 2, (i,j) if dim = 3, (i,j,k)”

Kind regards

that doesn’t make sense, what are you gonna do with i,j,k anyway if you don’t know how many of them (or even what variable names they will take on) ahead of time?

you can do a double loop maybe:

for element in Values
    for i in element

I suggest you also show what you do with the values later in the function

It is because I need it to index into a matrix, which can at times be dimensions = 2 or 3.

Perhaps I should find a way to make it into a single vector with some kind of linear indexing then

you can index a matrix by splitting the SVector:

julia> m = rand(2,2)
2×2 Matrix{Float64}:
 0.213414  0.272632
 0.48035   0.538782

julia> a = [1,2];

julia> m[a...]
0.2726319412873929

or use CartesianIndex, you can directly index a matrix with that.

1 Like

You don’t need SVectors for this. Just use either CartesianIndex or tuples:

vals = [(3,0,1), (2,3,4), (3,4,3), ...]

And then use splatting, as mentioned:

for ind in vals
    M[ind...] = 
end
1 Like

Don’t know who to mark as solution, thank you both guys!

@jling made me realize I was being stupid and should just index directly

@DNF made me realize that using StaticArrays for this kind of indexing thing is annoying, because one loses the ability to easily increment/decrement index - tuples are better here. StaticArrays shines very much in other parts of my code though :slight_smile:

Kind regards