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.
The following code will create a folder in your current working folder (pwd). The new folder will contain only the files that are relevant for this example. If you do not want to affect the current folder (or if you cannot generate files in this folder), change your working folder.
The run_balls.mrun_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.
% balls = run_balls(n) % Given 'n' number of balls, run a simulation until the balls come to a % complete halt (or when the system has no more kinetic energy). function balls = run_balls(n) %#codegen % Copyright 2010-2011 The MathWorks, Inc. % Seeding the random number generator will guarantee that we get % precisely the same simulation every time we call this function. old_settings = rng(1283,'V4'); % The 'cdata' variable is a matrix representing the colordata bitmap which % will be rendered at every time step. cdata = zeros(400,600,'uint8'); % Setup figure windows im = setup_figure_window(cdata); % Get the initial configuration for 'n' balls. balls = initialize_balls(cdata, n); energy = 2; % Something greater than 1 while energy > 1 % Clear the bitmap cdata(:,:) = 0; % Apply one iteration of movement [cdata,balls,energy] = step_function(cdata,balls); % Render the current state cdata = draw_balls(cdata, balls); refresh_image(im, cdata); end % Restore RNG settings. rng(old_settings);
First, generate a MEX function using the command codegencodegen 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.
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);
Speed up: x ~21.7
Remove files and return to original folder