How can I run my MATLAB files in PyCharm?

Viewed 4062

I'm currently taking an online course for machine learning, which required us to use the MATLAB Application. I was hoping (if possible) to do my exercises from the course in PyCharm instead.

I've installed the MATLAB Support plugin in PyCharm, and attempted to create an interpreter to run my .m files. But when clicking run or calling function in the console, I get errors such as the function doesn't exist or various syntax errors.

Any help would be appreciated!

3 Answers

I successfully run the MATLAB code on Pycharm, let main.py is your main python file that start the python project. you need to put the invoked matlab files in the same folder './' of the main.py that starts the program and inside the main.py you need to import the engine: import matlab.engine call your MATLAB code as described here 1. (this approach requires the MATLAB install) you can also use Matlab compile Package instead (not requires the MATLAB to be installed) 2.

  • you must have a supported version of the reference Python implementation (also known as CPython) installed on your system. MATLAB supports versions 2.7, 3.6, and 3.7.

To run your code: python main.py

I followed these steps: https://se.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-python.html

I went to interpreter settings in Pycharm and copied the interpreter path. I then went to configure the enviroment variables -> enviroment variables -> Path -> New: Here I pasted my interpreter path. Then I opened a terminal inside Pycharm and ran:

cd "matlabroot\extern\engines\python"
python setup.py install

NOTE: to find matlabroot type matlabroot in MATLAB.

This solved the problem for me. I tried without adding the interpreter path to enviroment variables, but when I did it worked. I'm not an expert so not sure why.

Try this :

import matlab.engine
eng = matlab.engine.start_matlab()
eng.simple_script(nargout=0)
eng.quit()

Be sure to add path of matlab file

Related