首页 > 解决方案 > How can I add all the elements of a Matrix using numpy?

问题描述

I have a function called check_sum that adds all the elements of an 2d array.

Grid is a 2d array, and grid_shape is 1024x1024.

I'm trying to use the numpy.matrix.sum function, but after several attempts I don't know how to implement it, it always gives me another value.

def check_sum(grid):
  xmax, ymax = grid_shape
  s=0
  for i in range(xmax):
    for j in range(ymax):
      s += grid[i][j]
  return s

标签: pythonnumpy

解决方案


您可以调用grid.sum()它,它将返回数组中所有条目的总和,无论它是 2d 数组还是 3d 数组。Sum()是一种通用的 numpy 方法,它适用于矩阵和数组。这里


推荐阅读