Clear Filters
Clear Filters

start the python engine via a script

6 views (last 30 days)
Uwe Brauer
Uwe Brauer on 5 Jul 2018
Answered: feriel on 3 Jun 2023
I am running Ubuntu 16.04, Matlab 2016b and emacs 27.
I started to use matlab's python engine basically to run matlab code in emacs via juypther and the matlab kernel engine. That works well, but I don't know really enough python to answer the following.
I start the engine via
>> import matlab.engine
>> eng = matlab.engine.start_matlab()
And I stop it via
Now the question is:
Can't I just write two scripts
import matlab.engine
eng = matlab.engine.start_matlab()
import matlab.engine
eng = matlab.engine.start_matlab()
And then run
$ python2 startmatlab
I tried but it did not work. What do I miss?
Uwe Brauer

Answers (2)

Siddharth Bhutiya
Siddharth Bhutiya on 11 Jul 2018

The issue here is that when the Python script ends, Python will automatically close the newly created MATLAB Engine. Hence you will not be able to access it.

In order to avoid that you can open a MATLAB instance and type the following command in the MATLAB command window:

>> matlab.engine.shareEngine('my_engine')

This shares the current MATLAB Engine and names it 'my_engine' so that you can connect to it from your jupyter notebook. You can also create a Python script to do this as follows:

import os
os.system('nohup matlab -minimize -r matlab.engine.shareEngine("my_engine")')

Once you have started the MATLAB Engine, you can use it in your code. Here is a simple example on how to do it.

import matlab.engine
eng = matlab.engine.connect_matlab('my_engine')
eng.sqrt(4.0) # You can put your code here

This will return the Python object for the MATLAB Engine named 'my_engine' and assign it to 'eng'. You can then execute whatever MATLAB code you want using the 'eng' Python object.

After you are done you can call 'eng.quit()' or simply close the MATLAB window to stop the MATLAB Engine.

Hope this helps.

Uwe Brauer
Uwe Brauer on 13 Jul 2018
thanks very much for this detailed answer. I will look into it and see how easy it is to use.
tane martin
tane martin on 20 Sep 2020
Hi Siddarth,
Are there any reasons this code structure would fail? I'm receiving some issues trying exactly this (posted here:

Sign in to comment.

feriel on 3 Jun 2023
classfication a un seul couche




Community Treasure Hunt

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

Start Hunting!