Home > Software design >  python: Is it possible to make another variable that contains a undefined variable?
python: Is it possible to make another variable that contains a undefined variable?

Time:08-04

The following code can be executed, but this code's problem is that it cannot be dynamically altered.

import numpy as np
def odes(x,t=0):        
    v_rates = np.array([x[0]*x[2], x[1], x[1], x[0]*x[3]])
    v_k     = np.array([[-1,1,1,-1],
                        [1,-1,-1,1],
                        [-1,1, 0,0],
                        [0, 0,1,-1]])
    return     np.matmul(v_k, v_rates)

print(odes([1,2,2,1]))

For my use I want to be able to use different versions of the v_rates-array, i.e. I would like to use v_rates as an argument such that the function becomes 'odes(x,t, v_rates)'. However, there is a problem: Due to x not being defined in advance, it is not possible to make another variable that contains a undefined variable. My question is how to define the function such that I can use another argument that can determine whether v_rates is version_1 or version_2 from below:

def version_1(x):
    return    np.array([x[0]*x[2], x[1], x[1], x[0]*x[3]])

def version_2(x):
    return    np.array([x[3], x[3], x[4], x[3]])

CodePudding user response:

You could pass in a function to your function that will get the v_rates

def odes(x,t=0, get_vrates_func=version1):
   v_rates = get_vrates_func(x) 

and then call it either with a default specified, or with your function or a lambda

odes(1,1)
odes(1,1,version2)
odes(1,1,lambda x: np.array(a,b,c,...))
  • Related