Student Lounge

Sharing technical and real-life examples of how students can use MATLAB and Simulink in their everyday projects #studentsuccess

一起使用matlab和python

Today’s blog is written by Heather Gorr, Product Marketing for MATLAB, and Deepak Bhatia, Education Marketing at MathWorks. In this blog, they share some important tips that will help you use MATLAB & Python together.

You’ve heard it before, MATLAB vs. Python (vs. R vs. ) but we’re going to talk about using MATLAB and Python together! (It can happen! And it does!) If you are a student, work in academia, or industry, you have probably encountered situations where you need to integrate work from more than one language. This is common in engineering and scientific applications, especially when they involve multiple teams and hardware needs. Such collaboration helped researchers atMIT CSAILleverage strengths of MATLAB and C++ together to detect color and movement changes imperceptible to the naked eye.

There’s a large community working on cool algorithms, teaching, and sharing examples in both languages – so why not take advantage of all this excellent work, independent of language preference!? For example, MATLAB and Python were used in building thisair quality prediction app和thissentiment analysis algorithm. The two languages are often used together for AI applications (so frequently that there are direct importers and exporters for deep learning networks throughMATLAB,ONNXTensorFlow)。

This blog will show you how to use MATLAB and Python together (in peace and harmony). We’ll assume a beginner-level background in both languages and provide links to more advanced topics.

The Basics

First, let’s get the requirements out of the way. We’ll need a recent version of Python and MATLAB R2014b or later (sounds like a good time to upgrade to R2020a!). Checkherefor version specifics.

This might sound obvious, but we’ll also make sure our code is accessible by both MATLAB and Python. The path can be updated easily from both languages.

从matlab调用python

在我们潜入之前,让我们确认Matlab可以找到Python解释器。我们可以用matlab做到这一点pyenv功能:

>> pyenv ans = pythonenvironment with属性:版本:“3.6”可执行文件:“c:\ python36 \ wpy-3670 \ python-3.6.7.amd64 \ python.exe”库:“c:\ python36 \ wpy-3670 \Python-3.6.7.amd64 \ python36.dll“主页:”c:\ python36 \ wpy-3670 \ python-3.6.7.amd64“状态:已加载的executionmode:OutofProcess ProcessID:”20980“processname:”matlabpyhost“

这返回Python版本和环境设置,也可以通过该系统进行修改pyenvfunction.

Now that we can access Python, let’s use it! We’ll try theSQRT.function from themath图书馆掌握它。在Python中,我们称之为:

>>> import math >>> math.sqrt(42) 6.48074069840786

To call the same Python function from MATLAB, we can use the following:

>> py.math.sqrt(42)ans = 6.480740698407860

我们用了format longto display the same precision in MATLAB and Python.

现在,让我们概括行为一点。使用以下语法访问Python模块和函数:

>> py.module_name.function_name.

以同样的方式被称为用户定义的模块。F要么example, theweather.pymodule in the air quality app includes functions which read weather data for a given location through a web API:

>> data = py.weather.get_current_weather("Boston","US",key) data = Python dict with no properties. {'coord': {'lon': -71.06, 'lat': 42.36}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'overcast clouds', 'icon': '04n'}], 'base': 'stations', 'main': {'temp': 53.2, 'feels_like': 34.9, 'temp_min': 51.01, 'temp_max': 55, 'pressure': 1003, 'humidity': 46}, 'visibility': 16093, 'wind': {'speed': 26.4, 'deg': 230, 'gust': 34.45}, 'clouds': {'all': 90}, 'dt': 1587342601, 'sys': {'type': 1, 'id': 3486, 'country': 'US', 'sunrise': 1587290159, 'sunset': 1587339006}, 'timezone': -14400, 'id': 4930956, 'name': 'Boston', 'cod': 200}

Notice that the output is a Python dictionary (in MATLAB!) We could convert this to a MATLAB type (more on data types to come), but for now we will continue to work with it directly. Let’s pull out the information of interest using another function from the module:

>> WeatherData = Py.Weather.Parse_Current_JSON(数据)数据= Python Dict,没有属性。{'temp':39.31,'feels_like':31.44,'temp_min':37,'temp_max':41,'压力':1010,'湿度':80,'速度':8.05,'deg':340,'城市':'波士顿','Lat':42.36,'Lon':-71.06,'Current_time':'2020-04-18 20:48:00.985146'}

我们还可以索引索引字典来调用特定值:

>> T = weatherData{"temp"} T = 39.3100

Notice that we used the curly brackets {} instead of parentheses (). In MATLAB, curly brackets are often used when accessing values from heterogeneous data types like cell arrays and tables. An easy way to remember is when you use (), you get a subset of a larger data set of the same type i.e. cell array or table. Conversely, if you use {}, you get the indexed value in its original data type i.e. double, string, char etc. Therefore, in the above example, a dict is a heterogenous data type and we will use {} to get the temperature value as a double. Thisexampleshows indexing into a Python dict.

Now that we’re getting the idea of syntax, let’s talk about another difference in calling functions. Say we wanted to change the units of the weather data. In Python, theget_forecast.function accepts standard Python keyword arguments, as shown in the last argument here:

>>> forecast = weather.get_forecast("Boston","US",key,units="metric")

In MATLAB, these are passed as name-value pairs with thepyargs功能:

>> forecast = py.weather.get_forecast("Boston","US",key,pyargs("units","metric")

现在我们了解如何使Python语法和来自MATLAB的呼叫函数调整。让我们另一边试试!还

Calling MATLAB from Python

TheMATLAB Engine API for Pythonenables calling MATLAB as a computation engine so we can use our favorite MATLAB functions from Python. First, we need to install it via the Python package included with MATLAB. Execute the following commands in an OS prompt:

$ CD“matlabroot./ extern / endines / python“$ python setup.py安装

matlabroot.“安装了MATLAB的目录(通过呼叫检查>>matlabroot.in MATLAB). Checkthis博文page for more info on setup.

Let’s get down to the fun part! To call MATLAB functions from Python, first import and start the engine (we could also use a current session of MATLAB if there is already one already跑步):

>>>导入MATLAB.ENGINE >>> ENG = MATLAB.ENGINE.START_MATLAB()

Now that the engine is running, let’s call the square root function:

>>> x = eng.sqrt(42.0) 6.48074069840786

请注意,我们正在呼唤SQRT.function with 42.0 and not simply 42. Stay tuned to learn why this is important in the next section.

MATLAB functions are called with their native syntax, but there are some distinct differences. One difference is in the way multiple outputs are captured. For example, in thesentiment analysis algorithm,MATLAB代码为情绪和分数返回多个输出。我们需要指定输出的数量露怪:

>>> [情绪,分数] = eng.sentimentAnalysis(文字,纳格语= 2)阳性[0.0,0.5109489640808081,0.48905110359191895]]

Similarly, if the MATLAB function returns no outputs (say the function writes results to a file), you need to pass露怪=0.

当我们完成了,我们should stop the MATLAB engine to free up system resources:

>>> Eng.exit()

To call MATLAB operators (like the famous backslash operator “\” to solve linear systems of equations), we need to use the function name (mldivide)。这是完整的清单MATLAB Operators and Associated Functions.

转换数据类型

When we calledSQRT.earlier, we used 42 in MATLAB but 42.0 in Python. Why the difference?

Typing42returns a double in MATLAB and an integer in Python. Our square root example would have errored without using the conversion functionfloat(42)要么typing42.0由于MatlabSQRT.accepts single, double, or complex types.

>>> eng.sqrt(42.0) 6.48074069840786 >>> eng.sqrt(float(42)) 6.48074069840786

We can also use integer and other type conversion functions (shown in the table below) in MATLAB to the pass expected types to Python functions.

That takes care of the inputs, but what about the outputs? We’ve seen a few examples already: in MATLAB,SQRT.returned a double, but the functions inweather.py返回Python字典对象。发生什么了?在可能的情况下,函数输出将由该语言的适当类型表示。否则,我们可以将数据转换为适当的类型。

The table below shows the mappings for common data types (a comprehensive list is included in the博文)。

桌子

Some specialized MATLAB data types liketimetable要么categoricalwill require some extra love and need to be converted manually. Of course, we can still use these data types in our functions, but the functions need to return types that the Python interpreter can understand.

桌子

Worried about all this data passing and conversion between MATLAB and Python? These can often be avoided by planning ahead. For example, in thesentiment analysis algorithmthe audio data are imported as integers (instead of the default double), which are then passed to the Python function directly.

使用文件来传输数据也是很常见的,特别是在跨团队和语言协作时。如果我们的数据是表格,我们可以使用Apache Parquet来传输两种语言之间的数据。matlab使用Apache arrow.to efficiently read and write data in Parquet. We can read the data, perform computations, and write the data to Parquet from several supported languages.

diagram

这是一个用于使用较大数据集的公共管道,可以帮助避免在转换中进行副本和额外的开销。查看this博文umentation page for more about how to read and write Parquet files in MATLAB.

Error Handling

到目前为止,我们谈到了如何避免错误,但让我们真实。错误发生在我们最好的中,并解释错误消息是一个有价值的技能。有些伟大的DOC页面是关于常见问题的故障排除,例如Python errors from MATLABMATLAB errors from Python.

我们可以整天花如何阅读错误消息,但这里最有用的教训是如何判断错误是否来自Matlab或Python。如果我们查看错误消息,我们将看到错误源自何处的指示。

我们来打电话SQRT.再次,但使用错误的数据类型:

>> py.math.sqrt("42") Python Error: TypeError: must be real number, not str

In MATLAB, we seePython错误在一行的开始处,其次是埃罗r raised from Python, which makes it easier to debug! MATLAB has caught the Python exception and rethrown it as a MATLAB exception containing the same message.

Let’s do the same from Python:

>>> eng.sqrt("42") Traceback (most recent call last): ... MatlabExecutionError: Undefined function 'sqrt' for input arguments of type 'char'.

The Python trace back is minimized here, but if we look at the last line, we seeMatlabExecutionError和the MATLAB error message. The MATLAB exception was caught and re-raised as a Python exception with the same message.

We’re keeping it simple, but there are more sophisticated ways to catch exceptions, which can be useful for testing and application sharing. Check out more infohere.

Creating Python Packages from MATLAB Code

So far, we’ve talked about using MATLAB from Python and vice versa, but we’ve assumed an installation of both on the same machine. How can we share our work with those who don’t have MATLAB installed? MATLAB Compiler SDK will let us package the MATLAB code and supporting files in other languages to be called from Python (or Java, C/C++, etc) and executed with a runtime. An app is also provided to help walk through the process and generate necessary files.

Theair quality prediction example使用此过程从MATLAB预测功能创建Python包,predictAirQual.m. We can use the Library Compiler App and select the function(s) to include (dependencies are automatically detected).

软件屏幕截图

This packages the files we need and creates asetup.pyreadme.txtfile with instructions for the Python steps.

To call this in Python, there is an installation step similar to the process for the MATLAB Engine API (instructionshere), using the generatedsetup.pyfile.

Then we need to import and initialize the package and can call the functions, like so:

>>> import AirQual >>> aq = AirQual.initialize() >>> result = aq.predictAirQual()

当我们完成后,通过终止该过程包装:

>>> aq.terminate()

空气质量示例进一步进一步分享用于在Web界面中使用的MATLAB功能(并立即访问许多用户)。在这种情况下,MATLAB Production Servercan be used for load balancing and the MATLAB code can be accessed through aRESTful API要么Python client.

We won’t go further here, except to share a few more resources and wrap up. The air quality and sentiment analysis examples are great to see how and why MATLAB and Python can be used together for amazing things! We’ve also created short videos using the sentiment example for callingPython from MATLAB和callingMATLAB from Python. There’s also a video discussing all of the above with theair quality example.

Hopefully by now you’ve realized you don’t need to pick favorites; you can use MATLAB and Python together! ?? We hope you enjoyed reading and found this blog useful. We’d love to hear what you’re working on and any questions you have! Comment below or through your preferred social media platform. ?

|
  • 打印
  • send email

注释

To leave a comment, please clickhereto sign in to your MathWorks Account or create a new one.