简体   繁体   English

如何使用 numpy 添加矩阵的所有元素?

[英]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.我有一个名为 check_sum 的 function ,它添加了二维数组的所有元素。

Grid is a 2d array, and grid_shape is 1024x1024. Grid 是一个二维数组,grid_shape 是 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.我正在尝试使用 numpy.matrix.sum function,但经过几次尝试我不知道如何实现它,它总是给我另一个价值。

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.您可以调用grid.sum() ,它将返回数组中所有条目的总和,无论它是 2d 数组还是 3d 数组。 Sum() is a general numpy method and it works both for matrices and arrays. Sum()是一种通用的 numpy 方法,它适用于矩阵和 arrays。 here 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 numpy 访问矩阵的相邻元素? - How can I access the neighboring elements of the matrix using numpy? 使用python矩阵M(使用numpy),如何将该矩阵的每一列与所有其他列进行比较? - With a python matrix M (using numpy), how can I compare each column of that matrix with all other columns? 如何使用 numpy 中的指定索引从 3D 矩阵中获取元素? - How can I get elements from 3D matrix using specified indices in numpy? numpy:如何使用矩阵元素作为索引? - numpy: How can I use matrix elements as index? 我如何用numpy将一个小矩阵添加到一个大矩阵中? - How can I add a small matrix into a big one with numpy? 如何在 python 的矩阵中打印特定值? (使用 numpy) - How can i print a specific value in matrix in python? (Using numpy) numpy csr矩阵的“均值”函数在所有矩阵上均值吗? 如何删除某个值? - Does numpy csr matrix “mean” function do the mean on all of the matrix? How can I remove a certain value? NXN矩阵的所有对角元素,而在python中不使用numpy - All Diagonal elements of a NXN matrix without using numpy in python 使用 numpy 将数组元素添加到矩阵的每一列 - Add elements of array to each column of matrix using numpy 如何使用 Numpy 将矩阵 x 的所有元素乘以矩阵 y 的所有元素? - How to use Numpy to multiply all elements of matrix x by all elements of matrix y?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM