Arbitrary parametric solutions can be exported to a standalone m-file by the @@PolyUnion/toMatlab@@ method. The exported file is completely MPT-independent and, more importantly, much faster to evaluate compared to built-in MPT evaluation code (which needs to perform lots of sanity checks which slow down the evaluation process).
The general syntax is as follows:
solution.toMatlab('name_of_file.m', 'function_to_export', 'tiebreak_function')
@]
The method takes any @@PolyUnion@@ object (or an array thereof) and exports the function @@function_to_export@@ to file @@name_of_file@@, resolving tiebreak (when a particular point is contained in multiple regions) using the function @@tiebreak_function@@. If you have a single optimizer that is continuous, you can use set @@tiebreak_function='first-region'@@. Here, the search for a region that contains a particular point is finished upon hitting the first such region.
The exported parametric solution can then be evaluated by
(:source lang=MATLAB :) [@
[z, region] = name_of_file(x)
@]
where @@x@@ is the vector of parameters at which to evaluate, @@z@@ is the value of the optimizer at @@x@@, and @@region@@ is the index of the region that constains @@x@@. If there is no region containing @@x@@, then @@z=NaN@@ and @@region=0@@.
To export explicit MPC feedbacks, use the following syntax:
(:source lang=MATLAB :) [@
controller.optimizer.toMatlab('name_of_file.m', 'primal', 'obj')
@]
This tells MPT to export the primal optimizer (stored as the @@primal@@ function of the @@optimizer@@ field of the controller), resolving tiebreaks using the cost function of the controller (stored as the @@obj@@ function of @@controller.optimizer).
Note that, by default, the @@toMatlab@@ method exports the full open-loop optimizer. In the case of explicit MPC this implies that the output of @@z=name_of_file(x)@@ will be an {$ N \times n_u $} vector, where {$ N $} is the prediction horizon and {$ n_u $} is the number of control inputs. Then the closed-loop control action is given by @@u = z(1:nu)@@. Alternatively, you can ask @@toMatlab()@@ to only export the closed-loop optimizer. This can be achieved by:
(:source lang=MATLAB :) [@
solution.trimFunction('primal', nu);
solution.toMatlab('name_of_file.m', 'primal', 'obj')
@]
Here, @@trimFunction('primal', nu)@@ will change the @@primal@@ function such that it only returns the closed-loop optimizer (i.e., the first @@nu@@ components of the open-loop optimizer).
Full example:
(:source lang=MATLAB :) [@