Package Code for Deployment with MATLAB Compiler SDK
Supported platforms: Windows®, Linux®, Mac
This example shows how use MATLAB® Compiler SDK™ to package a MATLAB function into a deployable archive and create a sample application to call the function. For more information on how application deployment works, see Steps for Deployment with MATLAB Compiler.
For this example, you create a Python® package and integrate it in a Python application generated by MATLAB Compiler SDK.
Prerequisites
Verify that you have met the system requirements for using MATLAB Compiler SDK and running Python applications. For details, see MATLAB Compiler SDK Python Target Requirements.
End users of compiled artifacts without access to MATLAB must install MATLAB Runtime. Artifacts built with MATLAB Compiler SDK require a matching version of MATLAB Runtime at the same update level or newer. You can include MATLAB Runtime in an installer for your Python package or install it separately. For details, see Download and Install MATLAB Runtime.
Create Function in MATLAB
Write MATLAB code that you intend to call in your target language application. Your MATLAB code must follow certain guidelines in order to be deployed. For more details, see Write Deployable MATLAB Code.
For this example, suppose your company's cost function, which represents the total cost associated with managing an inventory, is defined as follows:
D is the annual demand
Q is the order quantity
S is the order cost per order
H is the holding cost per unit per year
P is the purchase cost per unit
You can use the MATLAB function fminsearch
to find the order quantity
Q
that minimizes the total cost C(Q)
. Create a
function named fms.m
that takes an initial guess for order quantity,
annual demand, cost per order, holding cost per unit per year, and purchase cost per unit
and outputs the optimal order quantity and cost.
function [Q_optimal, cost_optimal] = fms(Q_initial_guess, D, S, H, P) cost_function = @(Q) D/Q * S + Q/2 * H + D * P; [Q_optimal, cost_optimal] = fminsearch(cost_function, Q_initial_guess) end
Create Sample MATLAB Script
MATLAB Compiler SDK can generate sample code in the target language that demonstrates how to call a MATLAB exported function. You can use the samples to implement your own application or to test the compiled artifact. For more details, see Create Sample Code to Call Exported Function.
Create a MATLAB sample script that calls your function with defined input values. Save the
following code in a sample file named
fmsSample1.m
.
% Sample script to demonstrate execution of function [Q_optimal, cost_optimal] = fms(Q_initial_guess, D, S, H, P) Q_initial_guess = 100; % Initialize Q_initial_guess here D = 10000; % Initialize D here S = 50; % Initialize S here H = 0.5; % Initialize H here P = 10; % Initialize P here [Q_optimal, cost_optimal] = fms(Q_initial_guess, D, S, H, P)
After packaging, the generated Python sample code calls your exported function using the same input values as in the corresponding MATLAB sample file.
Package MATLAB Code into Deployable Archive
You can build deployable archives at the MATLAB command line or using a graphical interface. For information on choosing which packaging method to use, see Choose Deployment Option.
For this example, build a Python package using the compiler.build.pythonPackage
function.
Build the Python package using the
compiler.build.pythonPackage
function and thefms.m
function. Use name-value arguments to specify the package name and add the sample file. You can specify additional options in thecompiler.build
command using name-value arguments. For details, seecompiler.build.pythonPackage
.buildResults = compiler.build.pythonPackage("fms.m", ... PackageName="Optimize", ... SampleGenerationFiles="fmsSample1.m", ... Verbose="on");
The
compiler.build.Results
objectbuildResults
contains information on the build type, generated files, included support packages, and build options.The function generates the following files within a folder named
OptimizepythonPackage
in your current working directory:samples\fmsSample1.py
— Python sample application.Optimize\__init__.py
— Python initialization code that facilitates importing your package.Optimize\Optimize.ctf
— Deployable archive that contains your Python package.GettingStarted.html
— HTML file that contains information on integrating your package.includedSupportPackages.txt
— Text file that lists all support files included in the package.mccExcludedFiles.log
— Log file that contains a list of any toolbox functions that were not included in the application. For information on non-supported functions, see MATLAB Compiler Limitations.pyproject.toml
— Configuration file that contains build system requirements and information, which are used bypip
to build the package. For details, seepip.pypa.io/en/stable/reference/build-system/pyproject-toml
.readme.txt
— Text file that contains packaging and interface information.requiredMCRProducts.txt
— Text file that contains product IDs of products required by MATLAB Runtime to run the application.setup.py
— Python script that installs theOptimize
package.unresolvedSymbols.txt
— Text file that contains information on unresolved symbols.
Note
The generated package does not include MATLAB Runtime or an installer. To create an installer using the
buildResults
object, seecompiler.package.installer
.
Install and Run Generated Sample Application
After creating your Python package, you can call the fms
function from a Python application. For information on creating applications that call packaged
MATLAB functions, see Integrate Artifact with Target Language Application.
This example uses the sample Python code OptimizepythonPackage\samples\fmsSample1.py
generated
during packaging. You can use this sample application code as a guide to write your own
Python application.
#!/usr/bin/env python
"""
Sample script that uses the Optimize package created using
MATLAB Compiler SDK.
Refer to the MATLAB Compiler SDK documentation for more information.
"""
import Optimize
# Import the matlab module only after you have imported
# MATLAB Compiler SDK generated Python modules.
import matlab
try:
my_Optimize = Optimize.initialize()
except Exception as e:
print('Error initializing Optimize package\\n:{}'.format(e))
exit(1)
try:
Q_initial_guessIn = matlab.double([100], size=(1, 1))
DIn = matlab.double([10000], size=(1, 1))
SIn = matlab.double([50], size=(1, 1))
HIn = matlab.double([0.5], size=(1, 1))
PIn = matlab.double([10], size=(1, 1))
Q_optimalOut, cost_optimalOut = my_Optimize.fms(Q_initial_guessIn, DIn, SIn, HIn, PIn, nargout=2)
print(Q_optimalOut, cost_optimalOut, sep='\n')
except Exception as e:
print('Error occurred during program execution\\n:{}'.format(e))
my_Optimize.terminate()
The Python sample application does the following:
Imports the
Optimize
packageUses a
try
-catch
block to handle exceptionsInitializes a
Optimize
object namedmy_Optimize
Creates
matlab.double
objects for each input argumentCalls the
fms
method and saves the output toQ_optimalOut
andcost_optimalOut
Prints the contents of
Q_optimalOut
andcost_optimalOut
Terminates the
my_Optimize
instance
At the system command prompt, navigate to the
MagicSquarePkgpythonPackage
folder. Install the
Optimize
package using the python
command.
python -m pip install .
For more information on installing Python packages, see Install and Import MATLAB Compiler SDK Python Packages.
If you have installed MATLAB Runtime, you can run the application at the system command prompt. For testing
purposes, you can also run the command in the MATLAB Command Window by preceding the command with the !
operator.
python fmsSample1.py
The Python sample application returns the same output as the sample MATLAB script.
1414.2135620117188 100707.10678118655
Note
On macOS, you must use the mwpython
script instead of
python
. For example, mwpython
fmsSample1.py
.
The mwpython
script is located in the
folder, where
matlabroot
/binmatlabroot
is the location of your MATLAB or MATLAB Runtime installation.
See Also
compiler.build.pythonPackage
| mwpython