MATLAB Answers

Use Matlab code in Python after creating standalone package

30 views (last 30 days)
Maryam Hamad
Maryam Hamad on 26 Aug 2020
Edited: Maryam Hamad on 11 Sep 2020
I am using MATLAB R_2020a and pycharm editor on MacOS, I want to use my MATLAB project in python code.
I followed the instruction to get the package, however, my MATLAB project has many folders and the generated folders after creating a package does not have any files inside the Sample folder as in MATLAB tutorial ( which includes the equivalent .py code).
My question is how to import in python the packge and how to start running the code and calling the functions inside the pycharm.
Any help is really appreciated.
here is a simple example of creating sumTwoNum MATLAB package for Python, and it has a sumTwoNum(a,b) function. please let me know how to call this function in python.

  0 Comments

Sign in to comment.

Answers (1)

Deepak Meena
Deepak Meena on 11 Sep 2020
Hi Maryam ,
The MATLAB Engine API for Python provides a package for Python to call MATLAB as a computational engine. The engine supports the reference implementation (CPython). MATLAB supports versions2.7, 3.6, and 3.7. So, make sure your python version is one of them.
Now let's assume the following MATLAB script sumTwoNum.m :
function m =sumTwoNum(a,b)
m = a + b;
end
Make sure that your MATLAB script is in MATLAB path.
Now you can call this function in python file test.pyas :
import matlab.engine
eng = matlab.engine.start_matlab()
p = eng.sumTwoNum(3,2);
print(p);
You can run the python script as follows
>python2 test.py
5
For more information,you can refer to this document

  1 Comment

Maryam Hamad
Maryam Hamad on 11 Sep 2020
Thank you Deepak Meena for your answer,
Actually, I am trying to use it as a package, without the need of MATLAB installation as here (Documentation).
I read that there is two ways to use MATLAB in Python, one of them exactly as you answered but the second one is by making a package that you just import it. The problem that I am facing is that I couldn't fined the .py file that I need to import after creating the package.

Sign in to comment.

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!