Home > Mobile >  In Python, how do I define an arbitrary number of indexed variables in a function?
In Python, how do I define an arbitrary number of indexed variables in a function?

Time:10-23

First off, thank you in advance for bearing with my novice understanding of Python. I am coming from MATLAB so hopefully that gives some context.

In MATLAB I define a mathematical function as:

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

In Python, I wrote:

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).

Below I have included the code for reference. 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).

import math, numpy as np

def gradFD(var_init,fun,hx):
    df = np.zeros((len(var_init),1)) #create column vector for gradient output


    # Loops each dimension of the objective function
    for i in range(0,len(var_init)):
        x1 = np.zeros(len(var_init)) #initialize x1 vector
        x2 = np.zeros(len(var_init))
        x1[i] = var_init[i] - hx
        x2[i] = var_init[i]   hx

        z1 = fun(x1)
        z2 = fun(x2)

        # Calculate Slope
        df[[i],[0]] = (z2 - z1)/(2*hx)
        


    # Outputs:
    c = df #gradient column vector

    return c

And the test script:

import math
import numpy as np
from gradFD import gradFD

def f(*x):
    return 2*x[0]**2   4*x[1]**3
    #return 2*x**2   4*y**3
var_init = [1,1] #point to evaluate equation at

c = gradFD(var_init,f,1e-3)
print(c)

CodePudding user response:

Array indexing in Python is done with square brackets, not parentheses. And remember that Python starts in indices at 0, not 1.

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

CodePudding user response:

Your function is called f but you are trying to call x(2). You get the error because you are trying to call x as a function, but x is a numpy array

  • Related