# Array of Arrays for months?

Hi,

I want to create an array of arrays, where each sub-array contains the period t (month). For example,
`t = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]`
`t = [ 13, 14, 15, 16 ...]`

and so on. I managed to do this using the following code,

``````T = fill(Int[], 5)
t = 1

while t <= 60
for i = 1:5
T[i] = [t, t+1, t+2, t+3, t+4, t+5, t+6, t+7, t+8, t+9, t+10, t+11]
global t = t + 12
end
end
``````

But of course, if the number of elements in the array is higher such as 20 or 30, it’s a very tedious process. Is there a better way to do this?

Thanks!

Is this what you’re after?

``````T = [collect(t:t+11) for t in 1:12:60]
``````
2 Likes

Yess that’s exactly what I wanted! Thank you, forgive my ignorance

Are you sure you actually need to collect these into an Array of Arrays? If you don’t need to mutate the elements you could use:

``````julia> T = reshape(1:12*5, 12, 5)
12×5 reshape(::UnitRange{Int64}, 12, 5) with eltype Int64:
1  13  25  37  49
2  14  26  38  50
3  15  27  39  51
4  16  28  40  52
5  17  29  41  53
6  18  30  42  54
7  19  31  43  55
8  20  32  44  56
9  21  33  45  57
10  22  34  46  58
11  23  35  47  59
12  24  36  48  60
``````

and index into it just like a Matrix:

``````julia> T[2,3]
26
``````

Then again, you could just calculate these values on the fly.

So I have an optimisation model where in some constraints I need to sum over the months for each year, for example:

``````@constraint(m, con[y = 1:Y], sum(x[t] for t in T[y])
``````

So for each year I need a set with the corresponding month numbers. I’m guessing I need to collect the numbers for this case yeah?

No, you don’t, since you don’t mutate anything in `T`. If I understand correctly, you want the sums of each 12th entries of `x`. A more efficient way to do this, would be to write this sum as:

``````sum(reshape(x, 12, :), dims=2)
``````

Here `reshape` first shapes your vector `x` into a matrix with 12 rows. Then `sum(..., dims=2)` sums along the 2nd dimension, so you get the sums of each row. You might still have to call `vec` on the result, because this returns a 12x1-matrix, but some code might explicitly require a vector.

Oh yes that works as well, but I just had to change `dims = 2` to `dims = 1`, because the reshape function arranges the elements from top to bottom instead of left to right, so I had to make it get the sum of each column instead of row, if that makes any sense. Thanks for that tip.