Calling C from MATLAB using the MEX interface
C is presently the lingua franca of computing.
If you are a C programmer, you should learn how to call the BLAS from C
and how to call C routines from MATLAB using MEX.
If you are not a C programmer, this is a good time to learn a little C.
MEX stands for MATLAB Executable. MEX-files are dynamically linked
subroutines produced from C or Fortran source code that, when compiled,
can be run from within MATLAB in the same way as MATLAB M-files or
built-in functions. You can find complete documentation on how to use
MEX in the MATLAB help facility, but the best way to learn is to look
at the examples here and change them carefully.
I strongly recommend that you use a Sun Solaris account when you use MEX.
Take a look at
Download this file and save it in whatever working directory you are using.
We can compile this program from inside MATLAB, but we need to use the right
MEX interface options, set in the file
Download this file and save it as a file
.matlab/R14/mexopts.sh in your home directory.
(If you use your own computer, you are on your own. You would have to figure
out how to set up the mexopts.sh options to call your C compiler (assuming you have one),
and you would have to install BLAS if they are not installed.)
Then, from the MATLAB prompt, type mex clgs.c and then
[Q,R] = clgs(A) as usual from the MATLAB prompt. What if you also have
a clgs.m file? Which one will it use? You can find out by typing which clgs.
Another way to make sure that MATLAB is really calling the C code
is to call it with only one output argument: Q = clgs(A): this should
generate an error message saying clgs.c requires two output arguments.
- clgs.c (C program for classical Gram-Schmidt (unstable),
together with MEX interface to BLAS in the Sun Performance library)
When you write your own C program to be called from MATLAB, use clgs.c as a template.
If you are new at C, don't be alarmed when you find you have tons of error messages.
The first thing to check is that your comments are written correctly. There are
two styles of comments: /*.....*/ often running over several lines (those extra *'s on
the lines in between are purely stylistic), and // for one-liners, usually on the same
line as actual code, but following it. Another common error is forgetting semicolons
which are required after every statement, unlike in Matlab.
The tough bugs, however, usually concern
allocation of space and parameter passing. Be very careful to follow the template
in the example file to avoid trouble.
You can also look (NOT READY YET...) at
This includes a sample mex interface for calling LAPACK routines. Use it
as a template for calling LAPACK. You have to change it appropriately
to do anything useful.
(a test program for LAPACK: it calls the QR factorization routine but
doesn't do anything useful and returns nothing)