Trouble converting data from MATLAB to Python

조회 수: 9 (최근 30일)
Alex Weaver
Alex Weaver 2020년 3월 10일
댓글: Kojiro Saito 2020년 3월 12일
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?

채택된 답변

Kojiro Saito
Kojiro Saito 2020년 3월 11일
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.
  댓글 수: 2
Alex Weaver
Alex Weaver 2020년 3월 11일
Any time I try any of the three I get "Unable to resolve the name py.dict." or whichever python command is trying to be used. I have tried adding the python files to the MATLAB search path but nothing seems to be working.
Kojiro Saito
Kojiro Saito 2020년 3월 12일
As described in this document,
First, Python 64bit version (installer is Windows x86-64 MSI installer as of Windows) is neccessary because current MATLAB (R2016a or later) only supports 64bit.
Second, if Python is not registered in Windows resigetry, you need to specify the Python exe path in MATLAB. For exampl, if Python exe is under C:\Languages\Python\python.exe, you need to do the following in MATLAB.
pyversion C:\Languages\Python\python.exe

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by