7

I am creating a Matlab toolbox for research and I need to execute Matlab code but also Python code.

I want to allow the user to execute Python code from Matlab. The problem is that if I do it right away, I would have to install everything on the Python's environment and I want to avoid this using virtualenv. The problem is that I don't know how to tell Matlab to user the virtual enviornment created.

maximovs
  • 113
  • 1
  • 7

2 Answers2

8

You can either modify the PATH environment variable in MATLAB prior to calling python from MATLAB

% Modify the system PATH so it finds the python executable in your venv first
setenv('PATH', ['/path/to/my/venv/bin', pathsep, getenv('PATH')])

% Call your python script
system('python myscript.py')

Or the better way would be to specify the full path to the python binary

system('/path/to/my/venv/bin/python myscript.py')
Suever
  • 64,497
  • 14
  • 82
  • 101
3

As suggested in comment by @tales-pádua you may use pyversion command to set path to Python executable you are using (before trying to call python from Matlab).

This can be automated by use of matlabrc.m file:

python = '.local/bin/python';
if exist(python, 'file')
    pyversion(python)
end
scrutari
  • 1,378
  • 2
  • 17
  • 33
  • This is supported from Matlab 2020a. The recommended command is [pyenv][1] [1]: https://mathworks.com/help/matlab/ref/pyenv.html – Vasco Apr 01 '20 at 07:30