本文介绍了是否可以使用 sympy 符号索引 numpy 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对这样的 numpy 数组做一些求和

Helle I want to do some summation on a numpy array like this

import numpy as np
import sympy as sy
import cv2

i, j = sy.symbols('i j', Integer=True)
#next read some grayscale image to create a numpy array of pixels
a = cv2.imread(filename)
b = sy.summation(sy.summation(a[i][j], (i,0,1)), (j,0,1)) #double summation

但是我遇到了错误.是否可以将 numpy 符号作为 numpy 数组的索引处理?如果不是,你能给我一个解决方案吗?谢谢.

but I'm facing with an error. is it possible to handle numpy symbols as numpy arrays'indexes? if not can you sugest me a solution?Thanks.

推荐答案

不能在 SymPy 表达式中直接使用 numpy 对象,因为 numpy 对象不知道如何处理符号变量.

You can't use numpy object directly in SymPy expressions, because numpy objects don't know how to deal with symbolic variables.

相反,使用 SymPy 对象象征性地创建您想要的东西,然后 lambdify 它.numpy 数组的 SymPy 版本是 IndexedBase,但它似乎存在错误,因此,由于您的数组是二维的,因此您也可以使用 MatrixSymbol.

Instead, create the thing you want symbolically using SymPy objects, and then lambdify it. The SymPy version of a numpy array is IndexedBase, but it seems there is a bug with it, so, since your array is 2-dimensional, you can also use MatrixSymbol.

In [49]: a = MatrixSymbol('a', 2, 2) # Replace 2, 2 with the size of the array

In [53]: i, j = symbols('i j', integer=True)

In [50]: f = lambdify(a, Sum(a[i, j], (i, 0, 1), (j, 0, 1)))

In [51]: b = numpy.array([[1, 2], [3, 4]])

In [52]: f(b)
Out[52]: 10

(另请注意,创建整数符号的正确语法是 symbols('i j', integer=True),而不是 symbols('i j', Integer=True)).

(also note that the correct syntax for creating integer symbols is symbols('i j', integer=True), not symbols('i j', Integer=True)).

请注意,您必须使用 a[i, j] 而不是 a[i][j],后者不受支持.

Note that you have to use a[i, j] instead of a[i][j], which isn't supported.

这篇关于是否可以使用 sympy 符号索引 numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:08