I have a two-dimensional array with sub-arrays of equal size, for example:
array = [
[10, 12, 15 ,17], [16, 32, 65, 47], [45, 48, 41, 23],
[36, 25, 74, 98], [32, 19, 66, 88]
]
I would like to create a new array by summing the corresponding elements of every 4th sub-array, i.e. the elements that are "on top of each other" in the above example:
new_array = [
[10 + 36, 12 + 25, 15 + 74, 17 + 98],
[16 + 32, 32 + 19, 65 + 66, 47 + 88],
[45, 48, 41, 23]
]
These are just examples, the actual arrays can be larger.
Complete Matrix
You can use
each_slice
,transpose
,map
andtranspose
again to navigate your matrix. The code first usesjoin('+')
to show what is being calculated :Warning!
You need to carefully select the
each_slice
parameter to suit your original array.transpose
might raise an exception otherwise :Incomplete Matrix
If the matrix
size
isn't a multiple ofwidth
:you could add subarrays full of 0s to get :
Array#fill does the job :