简体   繁体   中英

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

You can call grid.sum() and it will return the sum of all the entries in your array, no matter if it is a 2d or a 3d array. Sum() is a general numpy method and it works both for matrices and arrays. here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM