[英]Efficiently calculate cumulative sum of a multidimensional array?
If I have a 1D array arr[x]如果我有一个一维数组 arr[x]
cumulative_arr[x]=cumulative_arr[x-1]+arr[x]
For a 2D array arr[x][y]对于二维数组 arr[x][y]
cumulative_arr[x][y]=cumulative_arr[x-1][y]+cumulative_arr[x][y-1]-cumulative_arr[x-1][y-1]+arr[x][y]
How do I scale out this method for arrays of larger dimensions?如何为更大尺寸的 arrays 扩展此方法?
Cumulative Sum for a 4D array would be:- 4D 数组的累积总和为:-
cumulative_sum[w][x][y][z] = sum of arr[i][j][k][l] for all i<=w,j<=x,k<=y and l<=z.
I want to find a method for an N dimensional array.我想找到一个 N 维数组的方法。
Since you tagged as C++, here we go...由于您标记为 C++,因此我们在这里 go...
static const unsigned int ARRAY_CAPACITY = 64u;
int sum = 0;
sum = std::accumulate(&array[0], &array[ARRAY_CAPACITY], 0);
static const unsigned int MAXIMUM_ROWS = 32u;
static const unsigned int MAXIMUM_COLUMNS = 16u;
int sum = 0;
sum = std::accumulate(&array[0][0], &array[MAXIMUM_ROWS][MAXIMUM_COLUMNS], 0);
for
loops):三维(说明经典for
循环):int sum = 0;
for (int x = 0; x < CAPACITY_DIMENSION_3; ++x)
{
for (int y = 0; y < CAPACITY_DIMENSION_2; ++y)
{
for (int z = 0; z < CAPACITY_DIMENSION_1; ++z)
{
sum += array[x][y][z];
}
}
}
If the array slots are contiguous for all dimensions, you could cast the array as single dimension, and sum up as a single dimensional array.如果数组槽对于所有维度都是连续的,则可以将数组转换为一维,并总结为一维数组。
you can make a recursive function, like the one below:您可以制作递归 function,如下所示:
function dimensionalSum(arr: any[]){
if(typeof arr[0] == 'number'){
return arr.reduce((acc, num) => acc + num, 0);
}
return arr.reduce((acc, dim) => acc + dimensionalSum(dim), 0);
}
Note: The example is written in typescript, and it is just a proof of concept.注意:示例是用 typescript 编写的,它只是一个概念证明。
This way, it does not matter how many dimensions you have.这样,您拥有多少个维度并不重要。
If all you need is a way of computing the cumulative sum array over all dimensions of an arbitrary N-dimensional array, then, in Python, you could leverage the power of NumPy's cumsum()
:如果您只需要一种在任意 N 维数组的所有维度上计算累积和数组的方法,那么在 Python 中,您可以利用 NumPy 的cumsum()
的强大功能:
import numpy as np
def cumsum_all(arr):
result = arr
for i in range(arr.ndim):
result = np.cumsum(result, i)
return result
Testing this one would get:测试这个会得到:
arr = np.arange((2 * 3)).reshape((2, 3))
print(arr)
# [[0 1 2]
# [3 4 5]]
print(cumsum_all(arr))
# [[ 0 1 3]
# [ 3 8 15]]
arr = np.arange((2 * 3 * 4)).reshape((2, 3, 4))
print(arr)
# [[[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# [[12 13 14 15]
# [16 17 18 19]
# [20 21 22 23]]]
print(cumsum_all(arr))
# [[[ 0 1 3 6]
# [ 4 10 18 28]
# [ 12 27 45 66]]
# [[ 12 26 42 60]
# [ 32 68 108 152]
# [ 60 126 198 276]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.