0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MATLABのfevalをpythonで使いたい

0
Posted at

pythonの関数の定義

MATLABでは関数の中で使用したい関数をまとめて末尾にまとめて置けばよあったのだが,pythonでは関数の中の関数を使用する前に定義しておく必要がある.

MATLABのfeval (ハンドル関数?) みたいなものを使いたくてpython用に書き換えた.
なんとなく見た目は汚いが,同じ変数を異なる関数に繰り返し入れたい時に便利だと思う.

test_function.py
fx=0
fp=10000
fL=10
fW=60
fq=20
fdip=5
fnu=0.25

def chinnery(fu,x,p,L,W,q,dip,nu):
        
    def feval(funcName, *args):
        return eval(funcName)(*args)

    u=feval(fu, fx, fp, fq, fdip, fnu)\
        - feval(fu, fx, fp-fL, fq, fdip, fnu)\
            - feval(fu, fx, fp, fq-fW, fdip, fnu)\
                + feval(fu, fx, fp-fL, fq-fW, fdip, fnu)
    return u            

          
def myfunc(a,b,c,d,e):
    dp=a+b*c+d-e
    return dp
    
def myfunc2(a,b,c,d,e):
    dp3=a*b-c*d-e 
    return dp3
    
up=chinnery('myfunc', fx, fp, fL, fW, fq, fdip, fnu)

print(up)
# output: 600.0

関数chinneryの第1変数(関数内関数?の名前)を変えるだけで,いくつかの変数の組み合わせをそのままに,関数だけ変えることができる.
現在ではmyfunc, myfunc2のみだが,いくらでも増やせる.


 def feval(funcName, *args):
        return eval(funcName)(*args)

fevalでは第1変数に関数名をとって,第2変数以降の変数の数が可変である.

もしかしたらもっと便利な方法があるかもしれません.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?