Using Matlab to Generate C Code

Matlab 2011a has been capable of generating C code

Why C?
• You may need C for a given application.
• Matlab is painfully slow. MEX files can substantially increase computational speed.



Getting Started
You must set up Coder to work with your choice of compiler.
Enter
mex -setup
At the command line.
Enter y to see the list of installed compilers.
You will be presented with a choice of compilers, depending
on what is installed on your machine.
Select a supported compiler.
Enter y to verify your choice.
Note: “The default compiler that MathWorks supplies with MATLAB for Windows 32-bit platforms is not a good compiler for performance.” From MathWorks.


• Create a function m-file.
• Create the C source code using Matlab Coder.
• Create a main function to implement your
code.
• Compile with your choice of compiler.


Ex:
simple m-file multiplies its argument (h) by 2

function [z]= simple(h) %#codegen
z=h*2;
end

Notice the %#codegen pragma 
This notifies the Matlab code analyzer hat you will be attempting to make C code. The analyzer will now notify you of any conflicts that may arise when trying to translate your code to C.
Use Coder to write the C source code 



The window shown will open to the right of your screen.The “Entry-Point” is the function we want to execute, namely, the m-file, simple.m.

Because C requires that all variable types be explicitly declared, this is something we need to remedy.
Click on the gear-like icon to define h within Matlab.

Click the ‘Build’ tab and choose the C/C++
Executable option. Matlab warns us we need a ‘main’ function, but that is simply how C works.
Click the ‘Build’ button.


A ‘codegen’ directory will be created containing the required code.
Within the directory are more directories.
Continue down the tree to codegen\exe\simple where you will find the source code.