Question

I have a function that depends on several variables, let's say y=f(x1,x2,x3,x4). If each of the variables is a simple number, then the result should be a plain number. If one of the variables is an array, I need the result to be also an array. And so on: if two of the variables are arrays, I need the result to be a 2-dimensional array. Etc.

Example:

def f(x1,x2,x3,x4):
    y=x1*x2/(x3+x4)
    return y

x1=1.0
x2=2.0
x3=3.0
x4=4.0
f(x1,x2,x3,x4)
# should give 2.0/7.0 = 0.2857...

x3=array([1.0,2.0,3.0,4.0,5.0])
f(x1,x2,x3,x4)
# should give a one-dimensional array with shape (5,)

x4=array([10.0,20.0,30.0,40.0,50.0,60.0,70.0])
f(x1,x2,x3,x4)
# should give a two-dimensional array with shape (5,7)

How to do it? (To be as clear as possible for a non-Python reader of my program?)

Was it helpful?

Solution

The proper way to do this is to pass in the properly shaped data. If you want a 2d result, you should pass in 2d arrays. This can be accomplished by np.newaxis.

import numpy as np

def f(x1,x2,x3,x4):
    y = x1*x2/(x3+x4)
    return y

x1 = 1.0
x2 = 2.0
x3 = 3.0
x4 = 4.0
print f(x1,x2,x3,x4)

x3 = np.array([1.0,2.0,3.0,4.0,5.0])
print f(x1,x2,x3,x4)

x3 = x3[:, np.newaxis]
x4 = np.array([10.0,20.0,30.0,40.0,50.0,60.0,70.0])
x4 = x4[np.newaxis, :]
print f(x1,x2,x3,x4)

Of course, the way your question is posed, it's a little ambiguous why you should expect to get an array shaped (5, 7) and not an array shaped (7, 5).

OTHER TIPS

You might look at using @when to define the function appropriately.

For example:

# Case for single values
@when(int, int, int, int)
def f(x1,x2,x3,x4):
    y = x1*x2/(x3+x4)
    return y

# Case for 1D arrays
@when(list, list, list, list)
def f(x1,x2,x3,x4):
    y = []
    for i in range(len(x1)):
        y.append(x1[i]*x2[i]/(x3[i]+x4[i]))
    return y
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top