Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Tutorial: Using Matlab compiled classes from within Python

$
0
0

Unlike other Matlab features, it seems that usingMatlab compilerfor creating a python package is poorly documented. It took me quite some time, mostly by trial and error, to understand how to use Matlab classes (classdef) from within Python.

In this tutorial we will discuss the following basic Matlab class:

classdefBasicClass properties Value end methods function r = roundOff(obj) r = round([obj.Value],2); end function r = multiplyBy(obj,n) r = [obj.Value] * n; end end end Modifying theclass for efficient work from python classdefBasicClass < handle properties Value end methods function o = propValue(obj, propName) o = self.(propName); end function setPropValue(obj, propName, val) self.(propName) = val; end function r = roundOff(obj) r = round([obj.Value],2); end function r = multiplyBy(obj,n) r = [obj.Value] * n; end end end

We inherit our class from “ h andle” (Handle classes define objects that reference the object data. Copying an object creates another reference to the same data.)

Notice new propValue / setPropValue methods it is used for accessing public properties from Python (as long as I am aware, there is no similar built-in functions within auto-generated Python package.

Python example importMyPackage matEngine = MyPackage.initialize() myObj = matEngine.BasicClass() # Set property value matEngine.setPropValue(myObj, 'Value', 10) # Call our function result = matEngine.multiplyBy(myObj, 5) # Get property value print(matEngine.propValue(myObject, 'Value')) matEngine.terminate() print('OK') Compiling the package Follow standard MATLAB Compiler procedure for Python Select your class as an “exported function” Installing python package Run generated installer package and follow instruction:
./MyPackageInstaller_mcr.install Install the runtime into /home/user/MATLAB/MATLAB_Runtime Install the application into /home/user/MyPackage Install Python package:
sudopythonapplication/setup.pyinstall Running python example (linux)

Linux executionrequires proper LD_LIBRARY_PATH definition. Assuming our Matlab runtime is installed in /home/user/MATLAB/MATLAB_Runtime, we need to define it as the following:

exportLD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/home/${USER}/MATLAB/MATLAB_Runtime/v90/runtime/glnxa64:/home/${USER}/MATLAB/MATLAB_Runtime/v90/bin/glnxa64:/home/${USER}/MATLAB/MATLAB_Runtime/v90/sys/os/glnxa64:/home/${USER}/MATLAB/MATLAB_Runtime/v90/sys/opengl/lib/glnxa64 XAPPLRESDIR=/home/${USER}/MATLAB/MATLAB_Runtime/v90/X11/app-defaults

Execute Python example

Loading external MAT file within Matlab package

To successfully load the .mat file it needs to be placed within “Files required for your library to run” section within MATLAB Compiler project


Viewing all articles
Browse latest Browse all 9596

Trending Articles