%% Generate MEX Code to Accelerate Simulation of Bouncing Balls
% This example shows how to accelerate MATLAB® algorithm execution using a generated MEX function. It uses the codegen command to generate a MEX function for a complicated application that uses multiple MATLAB files. You can use codegen to check that your MATLAB code is suitable for code generation and, in many cases, to accelerate your MATLAB algorithm. You can run the MEX function to check for run-time errors.
%% Prerequisites
% There are no prerequisites for this example.
%% About the run_balls Function
% The run_balls.m function takes a single input to specify the number of bouncing balls to simulate. The simulation runs and plots the balls bouncing until there is no energy left and returns the state (positions) of all the balls.

type run_balls

%
%% Generate the MEX Function
% First, generate a MEX function using the command codegen followed by the name of the MATLAB file to compile. Pass an example input (-args 0) to indicate that the generated MEX function will be called with an input of type double.

codegen run_balls -args 0

%
% The run_balls function calls other MATLAB functions, but you need to specify only the entry-point function when calling codegen.
% By default, codegen generates a MEX function named run_balls_mex in the current folder. This allows you to test the MATLAB code and MEX function and compare the results.
%% Compare Results
% Run and time the original run_balls function followed by the generated MEX function.

tic, run_balls(50); t1 = toc;
tic, run_balls_mex(50); t2 = toc;

%
% Estimated speed up is:

fprintf(1, 'Speed up: x ~%2.1f\n', t1/t2);

%
% Copyright 2018 The MathWorks, Inc.