Main Content

Use the GPU to Simulate an MPC Controller in Simulink

This example shows how to generate CUDA® code and use the GPU to compute optimal MPC moves in Simulink®.

GPU Coder is required to run this example for both simulation and code generation.

Create Plant Model and Design MPC Controller

Use a double integrator as a plant.

plant = tf(1,[1 0 0]);

Create an MPC object for the plant with a sampling time of 0.1 seconds, and prediction and control horizon of 10 and 3 steps, respectively.

mpcobj = mpc(plant, 0.1, 10, 3);
-->The "Weights.ManipulatedVariables" property is empty. Assuming default 0.00000.
-->The "Weights.ManipulatedVariablesRate" property is empty. Assuming default 0.10000.
-->The "Weights.OutputVariables" property is empty. Assuming default 1.00000.

Limit the manipulated variable between –1 and 1.

mpcobj.MV = struct('Min',-1,'Max',1); 

Control the Plant Model in Simulink

Create a Simulink closed loop simulation using the MPC Controller block, with the mpcobj object passed as a parameter, to control the double integrator plant. For this example, open the preexisting gpudemo Simulink model.

open_system('gpudemo')

Accelerate Simulation Using NVIDIA GPU

To simulate the model using GPU acceleration, open the Configuration Parameters dialog box by clicking Model Settings. Then, in the Simulation Target section, select Generate acceleration.

You can now run the model by clicking Run or by using the MATLAB® command sim. Before running the simulation the model will generate CUDA code from the Simulink model and compile it to obtain a MEX executable. When the model is simulated, this file is called and the simulation is performed on the GPU.

sim('gpudemo')
-->Converting the "Model.Plant" property to state-space.
-->Converting model to discrete time.
   Assuming no disturbance added to measured output channel #1.
-->The "Model.Noise" property is empty. Assuming white noise on each measured output.

After the simulation, the plots of the two scopes show that the manipulated variable does not exceed the limit and the plant output tracks the reference signal after approximately 3 seconds.

Generate Code for NVIDIA GPU

To generate code that runs on NVIDIA GPU, open the Configuration Parameters dialog box by clicking Model Settings. Then, in the Code Generation section, select Generate GPU code.

You can now generate code by using the slbuild (Simulink) command, which also produces a Code Generation Report. Use evalc to capture the text output from code generation, for possible later inspection.

txt_out = slbuild('gpudemo');

Here, the entire Simulink model is generated to run on the GPU. To deploy only the MPC block on the GPU, you can create a model having only the MPC block inside. Typically in embedded control modules, the deployed model contains the controller block plus a few interface blocks for input/output signals.

See Also

Objects

Blocks

Related Examples

More About