Volume 5 No.1, Winter 2003

ISSN# 1523-9926

Converting M-Files to Stand-Alone Applications

Rafic Bachnak

Roger Lee

Rbachnak@falcon.tamucc.edu Leery@navair.navy.mil
Engineering Technology Avionics
Texas A&M University-CC Naval Air Systems Command

 

ABSTRACT

MATLAB has been recognized as the premier program for numerical computations and data visualization.  Due to the fact that MATLAB is an interpreted language, M-files execute slower than compiled programs written in other languages, such as C, C++, and Fortran.  Furthermore, M-files require the presence of MATLAB to run.  Recently, The MathWorks introduced a set of tools to automatically convert M-files into executable programs that will run independently of MATLAB.  This paper states the important features of the Compiler, describes the conversion process, and presents examples that illustrate the steps involved in creating stand-alone applications.  Test results that compare execution times of M-files and executable programs are also presented.

 

INTRODUCTION

MATLAB is a powerful language that simplifies the process of solving technical problems in a variety of disciplines by including a very extensive library of predefined functions.  It also offers many special-purpose tool boxes that address specific areas, such as signal processing and control systems, and provides Graphical User Interface (GUI) tools that make it suitable for application development.   Because of these capabilities, MATLAB has been recognized as the premier program for numerical computations and data visualization and has been used by the educational, industrial, and government communities all over the world.

 

Due to the fact that MATLAB is an interpreted language, MATLAB files (M-files) execute slower than compiled programs written in other languages, such as C, C++, and Fortran.  In addition, M-files require the presence of MATLAB to run.   To address these weaknesses, The MathWorks recently introduced a set of tools that automatically convert M-files into MEX files and C/C++ source code, which can then be compiled to produce stand-alone applications.  Stand-alone applications are executable programs that can run even if MATLAB is not installed on the system.  The tools required for generating stand-alone applications are: MATLAB, the MATLAB Compiler, the MATLAB C/C++ Math Library, and a C/C++ compiler.  The MATLAB C/C++ Graphics Library is also required to create stand-alone applications that make use of Handle Graphics® functions. The process of converting M-files to C/C++ files and creating stand-alone applications is described in three documents totaling over 1000 pages.  This paper describes the important features of the Compiler and its associated tools, states the benefits of converting M-files to MEX and stand-alone applications, and presents examples that illustrate the steps involved in the conversion process.

 

THE MATLAB® COMPILER

The MathWorks uses the phrase MATLAB Compiler, with a capital letter C, to refer to the product that translates M-files to C or C++ source code [1].  They also use the word "compiler" with a lowercase c to refer to the C or C++ compiler. The MATLAB® Compiler version 2.1 may be used to take M-files as input and produce the following outputs:

MEX-files run in the same workspace as the MATLAB interpreter, however, stand-alone C/C++ applications run independently of MATLAB.  There are four main reasons to compile M-files:  (1) To speed up the execution of programs: Compiled C or C++ code typically runs faster than its M-file equivalent, (2) To create stand-alone applications: These applications take advantage of the mathematical functions of MATLAB but do not require its presence to run, (3) To create C shared libraries or C++ static libraries:  The Compiler may be used to create a C shared library (dynamically linked libraries, or DLLs, on Microsoft Windows 95/98/2000/NT) or a C++ static library from an algorithm developed in MATLAB.   The algorithm may then be integrated into a C/C++ application, and (4) To hide proprietary algorithms: M-files are ASCII text files that anyone can view and modify.  MEX-files or stand-alone applications can not be viewed and modified.  The current Compiler supports most of the functionality of MATLAB, however, it cannot compile script M-files, function M-files that call a script, and function M-files that use objects.

 

THE MATLAB® C/C++ GRAPHICS LIBRARY

The C/C++ Graphics Library is a collection of graphics routines that make the MATLAB plotting and visualization capabilities available to stand-alone C and C++ applications [4].  The library contains more than 100 routines, including MATLAB 6.0 built-in graphics functions, such as surf, plot, get, and set, and some commonly used M-file graphics functions, such as newplot, gcf, gca, gco, and gcbf.  Using the graphics library with the Compiler and the C/C++ Math Library makes it possible to compile M-files that include lines, text, meshes, and polygons, as well as graphical user interface (GUI) components such as menus, push buttons, and dialog boxes.

 

The C/C++ Graphics Library does not support some MATLAB features, including MATLAB objects, MATLAB Java objects, plotedit command, and propedit command.  In addition to these restrictions, the graphics library provides limited support for certain callback coding practices.  Furthermore, the graphics library supports only a subset of print command switches to specify device drivers.  For example, the graphics library supports most of the MATLAB built-in drivers, such as the PostScript drivers, but it does not support any of the Ghostscript drivers.  The C/C++ Graphics Library is available for these platforms:  PCs running Microsoft Windows or Linux, Sun, HP, SGI, and Compaq Alpha UNIX platforms. The process of creating stand-alone applications is similar for both PC and UNIX machines.  To create a stand-alone graphics application, the Compiler is used along with the Graphics Library bundle file.  Bundle files are ASCII text files that contain Compiler command line options and arguments. For example, to compile an M-file called test1.m into a C application, the following command is entered the MATLAB prompt.

mcc -B sgl test1

This command invokes the Compiler, using the -B flag to specify the bundle file used to create C stand-alone graphics applications, sgl.  The first time the Compiler is run to create a stand-alone graphics application, it creates a subdirectory, named \bin, in the current working directory. The Compiler puts in these directory versions of the MATLAB menu bar and toolbar figure files that are used by stand-alone graphics applications at run-time.  The command for a C++ application is mcc –B sglcpp fname.

 

UNIX WORKSTATIONS

The Compiler supports the following UNIX Compilers:

·        The GNU C compiler, gcc, (except on HP and SGI64)

·        The system's native ANSI C compiler on all UNIX platforms

·        The system's native C++ compiler on all UNIX platforms (except Linux)

·        The GNU C++ compiler, g++, on Linux.

There are several restrictions regarding the use of supported compilers, including [4]:  (1) The SGI C compiler does not handle denormalized floating-point values correctly. Denormalized floating-point numbers are numbers that are greater than 0 and less than the value of DBL_MIN in the compiler's float.h file; (2) Due to a limitation of the GNU C++ compiler (g++) on Linux, try...catch...end blocks do not work; (3) The -A debugline: on option does not work on the GNU C++ compiler (g++) on Linux because it uses try...catch...end.

 

PC WORKSTATIONS

The Compiler supports the following ANSI C and C++ PC Compilers:

·        Lcc C version 2.4 (included with MATLAB)

·        Watcom C/C++ versions 10.6 and 11.0

·        Borland C++ versions 5.0, 5.2, 5.3, 5.4, and 5.5

·        Microsoft Visual C++ (MSVC) versions 5.0 and 6.0

The MATLAB installer should add the following path to the Windows operating system environment:  SET PATH=”%PATH%;C:\matlabr12\bin\win32”.   Selecting a C/C++ compiler is accomplished by typing “mbuild -setup <RET>”  then following the instructions. Although the Compiler supports the creation of stand-alone C++ applications, it does not support the creation of C++ MEX-files, on both UNIX and PC machines.

 

CREATING MEX FILES

Creating MEX-files on PC or UNIX workstations is a similar process.  The examples presented here were tested on a PC workstation running Windows.  The Compiler (mcc), when invoked with the -x macro option, translates M code to C code, generates a MEX wrapper, and invokes the mex utility, which builds the C MEX-file source into a MEX-file by linking the MEX-file with the MEX version of the math libraries (libmatlbmx).

 

The MATLAB interpreter dynamically loads MEX-files as they are needed.  Most MEX-files run significantly faster than their M-file equivalents.  Consider the M-file called “PolyRoots” shown in Fig. 1, which finds the roots of polynomial y=x^2 + x + 1. 

%*************************************************

% This program finds the roots of polynomial y=x^2 + x + 1   *          

%*************************************************

function PolyRoots

roots([1 1 1])

 

Fig. 1 M-file to find the roots of a polynomial

Typing PolyRoots at the MATLAB prompt will run the program and produce:

ans =

 

  -0.5000 + 0.8660i

  -0.5000 - 0.8660i

To create a MEX-file, the mcc command is used at the MATLAB prompt as follows.

mcc –x PolyRoots

This mcc command generates the following files:

PolyRoots.dll   

PolyRoots_mex.c 

            PolyRoots.h     

roots.h         

PolyRoots.c

 

PolyRoots.c contains MEX-file C source code

PolyRoots.h contains the public information

PolyRoots_mex.c containing the MEX-function interface (MEX wrapper)

PolyRoots.dll is the dynamic link library file of the the executable MEX-file

Roots.h is a header file that contains function prototype for roots.m

 

mcc automatically invokes mex to create PolyRoots.dll from PolyRoots.c and PolyRoots_mex.c. The mex utility encapsulates the appropriate C compiler and linker options for the system.  The MEX version of the file is invoked from the MATLAB interpreter the same way an M-file version is invoked.  Typing PolyRoots at the MATLAB prompt yields the same exact results as before.  Given an M-file and a MEX-file with the same root name in the same directory, the MEX-file takes precedence.  MATLAB runs the MEX-file version rather than the M-file version.

 

CREATING STAND-ALONE APPLICATIONS

A MathWorks utility, mbuild, provides an easy way to specify an options file that can be used to set the compiler and linker settings, change compilers or compiler settings, switch between C and C++ development, and build an application.  The Compiler (mcc) automatically invokes mbuild under certain conditions. In particular, mcc -m or mcc –p invokes mbuild to perform compilation and linking.  To prevent mcc from invoking mbuild automatically, the -c option can be used. For example, mcc -mc filename. On systems where there is exactly one C or C++ compiler, the mbuild utility automatically configures itself for the appropriate compiler.  On systems where there is more than one C or C++ compiler, the mbuild utility lets you select which of the compilers you want to use. Once a C or C++ compiler is selected, that compiler becomes the default compiler.  The user may later specify another compiler  by following the same procedure.

 

The Compiler, when invoked with the -m macro option, translates input M-files into C source code that is usable in any of the supported executable types. The Compiler also produces the required wrapper file suitable for a stand-alone application. Then, an ANSI C compiler compiles these C source code files and the resulting object files are linked against the C/C++ Math Library.   Similarly, the Compiler (mcc), when invoked with the -p macro option, translates input M-files into C++ source code that is usable in any of the executable types except MEX.  The source code for a stand-alone C or C++ application consists either entirely of M-files or some combination of M-files, MEX-files, and C or C++ source code files.  After compiling the C or C++ source code, the resulting object file is linked with the object libraries.

 

When you use the Compiler to compile an M-file, it generates C or C++ code, a header file, and a wrapper file.  The C or C++ code and the header file are independent of the final target type and target platform. That is, the C or C++ code and header file are identical no matter what the desired final output (i.e. MEX-functions, stand-alone applications, or libraries). The wrapper file, however, provides the code necessary to support the output executable type.  So, the wrapper file is different for each executable type.  Consider the M-file called “PolyVal” shown in Fig. 2.

%***************************************************************

% This program evaluates the polynomial y=x^4 + 2x^3 - x^2 + 4x - 5  at  x=5, 6

%***************************************************************

function y=PolyValue(poly,x)

poly=[1 2 -1 4 -5];

x=[5, 6];

y=polyval(poly, x)

 

Fig. 2  M-file to compute the value of a polynomial

This program evaluates a polynomial at two given points.  Typing PolyVal at the MATLAB prompt yields

ans =

         865        1711

To create an executable stand-alone file, the mcc command is used at the MATLAB prompt as follows

mcc -m PolyValue

This mcc command generates the following files:

PolyValue.h      

PolyValue_main.c 

bin              

PolyValue.c      

PolyValue.exe

PolyValue.h contains the public information.

PolyValue_main.c contain .EXE function interface (wrapper).

bin is a directory containing the MATLAB menu bar and toolbar figure files. 

PolyValue.c is the C source code.

PolyValue.exe is the executable application.

 

Note that when executing the mcc command to link files and libraries, mcc actually calls the mbuild script to perform the functions.  To run the stand-alone application, PolyValue, invoke it by typing its name on the MS-DOS command line. However, MATLAB offers a quick way to shell out to DOS by using the bang (!) function. The exclamation point character, “!”, is a shell escape and indicates that the rest of the input line is a command to the operating system. It is used to invoke utilities or run other programs without quitting from MATLAB.  At the MATLAB prompt type

!PolyValue

The application should run and display the same exact results as before.  After quitting the program, the operating system returns control to MATLAB.

 

To distribute a stand-alone application, a package containing the following files must be created: (1) The application executable, (2) The contents, if any, of the directory named bin, (3) Any custom MEX-files the application uses, and (4) All the MATLAB Math run-time libraries.  The C Math library has prepackaged all the MATLAB run-time libraries required by stand-alone applications into a single, self-extracting archive file, called the Math and Graphics Run-Time Library Installer (mglinstaller.exe).   On the PC, the installer is located in C:\matlabR12\extern\lib\win32\.   When run, the Installer will extract the libraries from the archive and install them in subdirectories of a directory specified by the user.

 

INPUTTING FROM THE KEYBOARD AND READING DATA FILES

It is often necessary to create interactive programs that allow the user to enter input from the keyboard.  Furthermore, in many applications, the input must come from previously generated data files stored in binary or MATLAB format. Consider the M-file program of Fig. 3.  This program, ReadDataFile, loads input data “signal” from a mat-file then calls a function, DispImg, to display the image of the data, “signal”.

%**********************************************************

% This programs loads data from an input file and displays the image      *

%**********************************************************

fname = input('Enter input file name (without extension [.mat]): ', 's');

tic

%load input data from matlab file *.mat

disp('STARTING: Load input data ...');

eval(['load ' fname]);

cuttail=0;                  %as defined in function Dispimg

dispimg(signal,'LIN',cuttail,0);  %call dispimg

toc                 %stop timer

 

Fig. 3  Loading a data file and displaying image

This program can be run at the MATLAB prompt by typing ReadDataFile as follows

>>ReadDataFile

>>Enter input file name (without extension [.mat]): test3

STARTING: Load input data ...

mean and standar deviation of real are 0.012599  0.51493

mean and standar deviation of imag are -0.012585  0.50625

magnitude min and max are 0  2.8454

threshold is 2.8454

display image in LIN scale

 

elapsed_time =

 

   37.6800

In addition to the above output, the program produces a graph representing the image of the input data “signal” as shown in the following figure.

As stated earlier, the Compiler does not support the INPUT function to manipulate workspace environment.  Therefore, the Compiler can not correctly compile the program of Fig. 3.  To get around this restriction, one can manually edit the C code generated by the Compiler.  This approach, however, is inefficient and not practical.  The C/C++ Graphics Library offers an input dialog box MATLAB function, INPUTDLG, which can be used to automatically solve this problem.  The above example may be modified as shown in Fig. 5. The modified program consists of a main function, ReadDataFile2, which calls two functions, LoadInput and DispImg.  Creating a stand-alone application by writing the source code in more than one M-file is very practical.  This approach allows the programmer to take advantage of MATLAB's interpretive development environment.  After getting the M-file version of the program to work properly, the code is compiled and converted into a stand-alone application.

%**********************************************************

% This programs loads data from an input file and displays the image      *

%**********************************************************

function ReadDataFile2

% prompt for input file name

prompt={'Enter input file name (without extension [.mat]): '};

tic                 %start timer

title2='Input File name';

lines=1;

defaultfn={'test250'};

fname1 = inputdlg(prompt, title2, lines, defaultfn);

fname=fname1{1}     %extracting the first element in the array

%

signal=loadinput(fname);  %call loadinput to read file

cuttail=0;                  %as defined in function Dispimg

dispimg(signal,'LIN',cuttail,0);  %call dispimg

toc                 %stop timer

 

Fig. 5 Loading a data file and displaying image

We show in Fig. 6 the function that reads the input data file as requested by ReadDataFile2, LoadInput.

%*************************************

%This function reads an input data file (.mat)     *

%*************************************

function signal=loadinput(fname1)

% Reading input signal                     

load(fname1, 'signal');

 

Fig. 6 Function to read an input data file

Since ReadDataFile2 uses a graphics library function, the graphics library must be included when compiling the file as follows

mcc -B sgl ReadDataFile2 dispimg loadinput

This command creates an executable file, ReadDataFile2.exe, which can be run at the MATLAB prompt by typing

!ReadDataFile2

Running the program produces the following input box

Instead of the default “test250”, the user can type in a desired file name.  After clicking on OK, the program produces the same exact results as before (except a different execution time). 

CREATING AND TESTING A STAND-ALONE REAL APPLICATION

The examples presented so far require little time to execute.  To illustrate the benefits of the Compiler and its associated libraries, a program that implements the Range Migration Algorithm for Synthetic Aperture Radar (SAR) image formation was used.  The program, which is not shown here, consists of a main function (rma8c) and six subfunctions.  The executable code is produced by typing

mcc -B sgl rma8c loadinput dispimg localmax stolt_int2 resol3db invpaint

 

The program was run at the MATLAB prompt by typing

                        !rma8c

 

To compare the execution speed of M-files, MEX files, and EXE files, rma8c was run on a 1GHz machine with these three types.  The upper part of Table 1 summarizes the results.

Table 1 Comparison of execution times

 

 

Execution time (seconds)

Machine

File

Run #

M-File

MEX-file

.EXE C

Ratio (.EXE/M-file

1 GHz PC,

128 MB RAM

Rma8c

1

734.24

397.43

328.40

0.447

2

739.15

405.51

331.26

0.447

1 GHz PC,

128 MB RAM

Rma8cs

1

688.55

339.99

306.48

0.445

2

690.31

338.67

305.39

0.442

A shorter version of Rma8c, Rma8cs, was created by removing code that generates several intermediate graphs. Rma8cs was run on the same machine and the results are shown in the lower part of Table 1.

Summary of Commands

The following summarizes how to use the MATLAB Compiler to generate some of the most common results.  The commands apply to both UNIX and PC machines.  Note that you can add the -g option to any of these commands for debugging purposes.

Converting from MATLAB to MEX Files

To convert an M-file into C and create the corresponding MEX file that runs at the MATLAB prompt:

mcc –x mainfn sub1fn sub2fn

 

Converting from MATLAB to EXE Files (C compiler)

To convert an M-file into C and to create a corresponding stand-alone executable file that can be run without MATLAB (at the DOS prompt), use:

mcc –m mainfn sub1fn sub2fn

 

To convert an M-file that contains Handle Graphics functions into C and to create a corresponding stand-alone executable file that can be run without MATLAB (at the DOS prompt), use:

mcc –B sgl mainfn sub1fn sub2fn

 

Converting from MATLAB to EXE Files (C++ compiler)

To convert an M-file into C++ and to create a corresponding stand-alone executable file that can be run without MATLAB (at the DOS prompt), use:

mcc –p mainfn sub1fn sub2fn

 

To convert an M-file that contains Handle Graphics functions into C++ and to create a corresponding stand-alone executable file that can be run without MATLAB (at the DOS prompt), use:

mcc –B sglcpp mainfn sub1fn sub2fn

 

Converting from MATLAB to C Code

To produce a C file from an M-file (and functions), use:

mcc –mc mainfn sub1fn sub2fn

To produce a EXE file from a C file, use:

mbuild mainfn sub1fn sub2fn

 

Creating Libraries

To create a C library, use mcc -m -W lib:libfoo -T link:lib foo.m.   To create a C++ library, use: mcc -p -W lib:libfoo -T compile:lib foo.m.

 

To create a C shared library that performs specialized calculations that you can call from your own programs, use: mcc -W lib:mylib -L C -t -T link:lib -h Function1 Function2 ...

 

Conclusion

MATLAB files execute slower than compiled programs written in other languages, such as C, C++, and Fortran.  In addition, M-files require the presence of MATLAB to run.   The MathWorks recently introduced a set of tools that automatically convert M-files into C/C++ source code, which can then be compiled to produce stand-alone applications. This paper discusses the major features of the Compiler suite, describes the benefits of compiling M-files, and presents examples that illustrate the steps involved in the conversion process.  Test results show that execution time of .EXE files is less than 50% of that of M-files.  While the Compiler offers an easy way to convert M-files to stand-alone applications, it has some major limitations.

 

References

1.      The MATLAB Compiler User’s Guide Version 2.1 (264 pages).

2.      The MATLAB C Math Library User’s Guide Version 2.1 (332 pages).

3.      The MATLAB C Math Library Reference Version 2.1 (429 pages).

4.      The MATLAB C/C++ Graphics Library Version 2.0 (52 pages).

 

 Return to This Issues Home Page