简体   繁体   English

在 Python 中,如何在函数中定义任意数量的索引变量?

[英]In Python, how do I define an arbitrary number of indexed variables in a function?

First off, thank you in advance for bearing with my novice understanding of Python.首先,预先感谢您对我对 Python 的新手理解。 I am coming from MATLAB so hopefully that gives some context.我来自 MATLAB,所以希望能提供一些背景信息。

In MATLAB I define a mathematical function as:在 MATLAB 中,我将数学函数定义为:

f =@ (x) 2*x(1)^2 + 4*x(2)^3

In Python, I wrote:在 Python 中,我写道:

def f(x):
   return 2*x(1)**2 + 4*x(2)**3

But I get an error inside my other function (finite difference method for creating gradient vector):但是我在另一个函数中出现错误(用于创建梯度向量的有限差分方法):

line 9, in f
    return 2*x(1)**2 + 4*x(2)**3
TypeError: 'numpy.ndarray' object is not callable

(an input X1 that contains n-number of entries, specified by the number of variables in the original equation, is fed back into the function f(x) to evaluate at a specific point). (包含 n 个条目的输入 X1 由原始方程中的变量数指定,被反馈到函数 f(x) 以在特定点进行评估)。

I am happy to share the code I have written so far (or the working code in MATLAB) for reference, but the main thing I am wondering is how I can create an arbitrary number of variables for an equation like I do in MATLAB with x(1),x(2)...x(n).我很高兴分享我到目前为止编写的代码(或 MATLAB 中的工作代码)以供参考,但我想知道的主要问题是如何像在 MATLAB 中使用 x 那样为方程创建任意数量的变量(1),x(2)...x(n)。

Array indexing in Python is done with square brackets, not parentheses. Python 中的数组索引是用方括号完成的,而不是圆括号。 And remember that Python starts in indices at 0, not 1.请记住,Python 的索引从 0 开始,而不是 1。

def f(x):
    return  2*x[0]**2 + 4*x[1]**3

Your function is called f but you are trying to call x(2) .您的函数名为f但您正在尝试调用x(2) You get the error because you are trying to call x as a function, but x is a numpy array您收到错误是因为您试图将x作为函数调用,但x是一个 numpy 数组

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

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