MATLAB Coder

Hello World

This example shows how to generate a MEX function from a simple MATLAB function using the 'codegen' command. 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.

Create a New Folder and Copy Relevant Files

The following code will create a folder in your current working folder (pwd). The new folder will only contain 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), you should change your working folder.

Run Command: Create a New Folder and Copy Relevant Files

coderdemo_setup('coderdemo_hello_world');

About the 'hello_world' Function

The hello_world.mhello_world.m function simply returns the string 'Hello World!'.

type hello_world
function y = hello_world %#codegen
y = 'Hello World!';

%   Copyright 2010 The MathWorks, Inc.

The %#codegen directive indicates that the MATLAB code is intended for code generation.

Generate the MEX Function

First, generate a MEX function using the command codegencodegen followed by the name of the MATLAB file to compile.

codegen hello_world

By default, 'codegen' generates a MEX function named 'hello_world_mex' in the current folder. This allows you to test the MATLAB code and MEX function and compare the results.

Run the MEX Function

Run the MEX function to compare its behavior to that of the original MATLAB function and to check for run-time errors.

hello_world_mex
ans =

Hello World!

Cleanup

Remove files and return to original folder

Run Command: Cleanup

cleanup