I needed to run matlab script from python script. I wanted to pass several input arguments from pandas DataFrame, perform calculation in matlab and return multiple output arguments back to python.
- Install matlab engine API for python:
In your terminal, go to directory where matlab is install and run installation python script, e.g.:
$ cd /Applications/MATLAB_R2020a.app/extern/engines/python
$ python3 setup.py install
(warning - I found out that python3.9 is not supported by Matlab2020a and I had to use python3.7)
- Create virtual enviroment with site-packages (i.e., include installed
matlab.engine
):
$ python3 -m venv venv --system-site-packages
- Activate virtual enviroment:
$ source ./venv/bin/activate
- Create example python script:
my_python_script.py
:
import matlab
import matlab.engine
import pandas as pd
# Create example pandas DataFrame
dictionary = {'column_1': [1, 2, 3, 4, 5], 'column_2': [3, 5, 6, 1, 2]}
df = pd.DataFrame(data=dictionary)
# Convert series from pandas DataFrame to type recognizable for matlab
input_1 = matlab.double(df['column_1'].values.tolist())
input_2 = matlab.double(df['column_2'].values.tolist())
# Directory with matlab script (MacOS style)
script_dir = '/Users/<your_user_name>/Documents/python_projects'
# Start matlab engine
eng = matlab.engine.start_matlab()
# Update path to script in matlab with path to directory with your script
eng.addpath(script_dir)
# Call matlab script with 2 input and two output arguments
output_1, output_2 = eng.my_matlab_script(input_1, input_2, nargout=2)
# Print results
print(output_1)
print(output_2)
NB - when you have your matlab file located in another directory than your python script, or when current directory is changed inside python script, it is necessary to update matlab path with eng.addpath(script_dir)
command as showed above.
- Create example matlab script:
my_matlab_script.m
:
function [output_1, output_2] = my_matlab_script(input_1, input_2)
% Simple matlab script with 2 input and 2 output parameters
% Script computes max and median
output_1 = max(input_1);
output_2 = median(input_2);
end
- In your activated venv run:
$ python3 my_python_script.py
# Call matlab script with 2 input and two output arguments
output_1, output_2 = eng.my_matlab_script(input_1, input_2, nargout=2)