I want to create an array of arrays, where each sub-array contains the period t (month). For example, t[1] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12] t[2] = [ 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?
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.