MATLAB: Trouble converting data from MATLAB to Python

MATLABpython

I'm just trying to get a basic understanding of how the data types are converted. I have seen the help pages on the Mathworks website, but they don't seem to offer an example. I am trying to run python scripts in MATLAB.
The matlab code is
x = 4;
system('python pythontest.py');
The python script is
y = x*5
print(y)
So how do I get the x to carry over to python?

Best Answer

I think there are three ways.
(1) Use buitin Python functions by py.eval
x = 4;
workspace = py.dict(pyargs('x',x));
y = py.eval('x*5', workspace)
Python's eval does not allow variable assignment such as y=x*5, so here is another way by py.exec.
(2) Use buitin Python functions by py.exec
x = 4;
workspace = py.dict(pyargs('x',x));
py.exec('y=x*5;print(y)', workspace)
(3) Call Python class.
First, make the python script as a class.
pythontest.py
class Test:
def test(x):
y=x*5
print(y)
Call this Python class from MATLAB.
x = 4;
%% Import custom Python module
myClass = py.importlib.import_module('pythontest');
myClass.Test.test(x)
For detail, please refer to the document.
Related Question