I have a Windows Matlab R2020a and was able to generate C source code for my Matlab function. However, I need to run a MEX file (for speed) on a Linux platform which has a Matlab installed (without Coder) and no way to install it (even trial version).
Please, provide the steps to compile this Matlab-generated C code on the linux (Ubuntu) system. I guess it can be done with gcc. I am unable to find a clear description on the web, as this process seems extremely complicated due to the obscure command line args needed to give to gcc (and i only rarely compile C code).
Please, note that generating C code using the MATLAB Coder App is not enough if you need a MEX
file. MEX
files have to contain a mexFunction
function, which is not generated by the Coder App.
As a first step, I'd make sure your compiler is supported by MATLAB for the creation of MEX files. You can find the supported compilers on Linux here. Then I'd check whether the compiler is setup for Matlab to use it, as shown here. Finally, I'd have a look at some examples provided by Mathworks themselves: here
Once the C
code (with the mexFunction
) is ready, you can compile it using the mex
command and use it on the Linux platform with no or minimal adjustments, depending on how heavily you rely on the functions defined in mex.h
(which is the header your C
file will have to import if you want to generate a MEX
file).
You need the interface provided by the mexFunction
for Matlab to be able to exchange inputs and outputs with the compiled function. Note that you can create other standard C functions (possibly defined in other C
files) and call them from within the mexFunction
as you would normally do in C
. Basically, you can create your own libraries in C
and then use them in Matlab via dedicated mexFunction
s.
mex.h
also provides the API to "convert" C
data structures into Matlab data structures (e.g. arrays, cell arrays etc., all via the mxArray
type).
There's a bit of a learning curve, mostly spent in understanding how to convert data back and forth between standard C
and Matlab, but it's certainly worth your while. With a bit of care (e.g. switching to mxArray
types only when absolutely necessary), you can end up having libraries of functions that can be used in standard C
programs as well as in Matlab applications