How to run MATLAB code from within Python

后端 未结 1 1093
鱼传尺愫
鱼传尺愫 2020-12-09 19:11

I am trying to run a MATLAB code using Python (I\'m using python 3.6).

I don\'t need to pass any arguments or get any outputs. I just need a line of code on Python t

相关标签:
1条回答
  • 2020-12-09 19:51

    Using Oct2Py

    Your first option is using Oct2Py which runs with Octave, a free and opensource Program that can run Matlab files and functions. Just install it with the following Terminal command:

    pip3 install oct2py
    

    Then you can run MatLab Code from your Python script like that:

    from oct2py import Oct2Py
    oc = Oct2Py()
    
    
    script = "function y = myScript(x)\n" \
             "    y = x-5" \
             "end"
    
    with open("myScript.m","w+") as f:
        f.write(script)
    
    oc.myScript(7)
    

    Using MatLab

    If you want to use the original MatLab engine you would have to follow the following steps:

    1. Installing the MatLab library

    Following the instructions of this page you first have to find your MatLab root folder by opening MatLab and running the command matlabroot. This should give you the root folder for Matlab.

    Then you open your terminal (if you are using Windows you can do that by pressing Windows + R, then type cmd and press Enter.) In the terminal you run following code:

    cd matlabroot\extern\engines\python
    

    Make sure to replace matlabroot with the Path you just found. Then you run

    python3 setup.py install
    

    To install the MatLab Python library.

    2. Using the MatLab Library

    Following the instructions of this page You can then

    import matlab.engine
    
    eng = matlab.engine.start_matlab()
    tf = eng.isprime(37)
    print(tf)
    

    If you want to run entire scripts, you can save your scripts as a MatLab *.m file in your current folder and run them like this:

    import matlab.engine
    eng = matlab.engine.start_matlab()
    eng.myMatlabFile(nargout=0)
    

    You could also create the MatLab File from Python:

    import matlab.engine
    
    script = "b = 5;\n" \
             "h = 3;\n" \
             "a = 0.5*(b.* h)"
    
    with open("myScript.m","w+") as f:
        f.write(script)
    
    eng = matlab.engine.start_matlab()
    eng.myScript(nargout=0)
    

    I hope this helps :)

    0 讨论(0)
提交回复
热议问题