Interfacing MATLAB with C/C++ programs - c

Hi I wanted to know how to use MATLAB as an external solver from a C program. Specifically in my code I wish
to solve several linear systems of the form Ax=b.
I have heard that to go the other way namely Calling C functions in a MATLAB routine one uses MEX files.But I am not really sure how to use Mex files either.
Thank you

Actually, MEX files allow you to include C code in Matlab programs, for example if you want to use external C libraries in Matlab.
What you want to do is use the Matlab Engine:
http://www.mathworks.com/help/techdoc/matlab_external/f29148.html
As an alternative, you could use linear algebra libraries that are written purely in C, such as LAPACK and BLAS. ( www.netlib.org )

you can use the matlab engine as Lagerbaer points out. However sometimes it can be convenient just calling the matlab process commandline style. I use this often when I don't want to mess with mxArrays etc, or when the amount of matlab code that needs executing gets really large. PseudoCode:
WriteArrayInMFormat( "in.m", myInputNumbers );
LaunchProcess( "matlab", "-nodesktop -r \"myFunction( 'in.m' )\" -logfile out.m" );
ReadArrayInMFormat( "out.m", myResult );
For me this is especially useful when testing things out: instead of having to recompile the C/C++ program each time I change something, I just apply all changes in the myFunction.m file. At that point I don't even need the C program, instead everything can be tested in matlab.

Related

Does Matlab Coder produces single threaded C applications only?

Is Matlab Coder only able to produce single threaded applications?
I attempted to convert some Matlab scripts, used for image analysis, and found that the code produced by Matlab Coder was much slower. This confused me because I thought the produced C code would be at-least as fast or faster then the M code. I then checked how many threads were being used for both the M code and the produced C code. The result was 1 thread used by the C code and there were many threads being used by the Matlab code. At this point I can only assume the image processing toolkit implements its function as mex functions which are multi-threaded.
While in general the generated code can be expected to be faster, there are some exceptions. Some implementations which are used by matlab are not available for generated code. I have no reference about the technical background, but I assume that these are fortran and/or assembler written libraries. An example for such a function is eig which is known to produce different (correct) results in generated code.
The matlab coder comes with a code examples which explains how a parfor is translated to openmp code. As a first step make sure that your code contains the openmp relevant pragmas. If not try rewriting your code using a parfor loop.
In a last step, make sure that your compiler is configured to use openmp.

Is there any difference between a mex file and a function called with coder.ceval?

related
My goal is to use a mix of C code and Matlab code, and ultimately have the whole thing run in C by using the Coder tool.
I've found 2 ways of incorporating C into Matlab, writing a Mex file, and using coder.ceval on a C program.
Is there any difference in these 2 methods, beyond just calling syntax?
I'll compare creating a hand-written MEX file against using MATLAB Coder to integrate custom C code using coder.ceval.
Similarities
In both cases, a MEX file can be produced that you can call in MATLAB like any other MATLAB function. A hand-written MEX function will be compiled using the mex command from C source code you write. With MATLAB Coder the MEX file will be automatically generated from MATLAB code that calls your C code via coder.ceval using either the codegen command or the MATLAB Coder App.
Some Basic Differences
(note I use C throughout, but C++ can be used for MEX files as well)
When writing a MEX file, it is necessary to manually move your data between mxArray values and native C types. You'll need to use the MEX library and the C/C++ Matrix Library to do this. If coder.ceval is used, a MEX file can be auto-generated from your MATLAB code that does this data marshalling for you.
A single hand-written MEX file can be made to work with a variety of MATLAB data types. MATLAB Coder requires the type, size (arrays can also be made variable-size), and complexity of each argument to be declared. For example, if you want a MEX file that takes double and single values for a given input, then one MEX file must be generated for each input type.
With a handwritten MEX file, once the data is retrieved from the mxArray values provided by MATLAB, arbitrary C code can be written to manipulate it. coder.ceval requires that you write MATLAB Coder compatible MATLAB code to call the C functions using the external code interfaces it provides. For functions with simple interfaces, e.g. those taking numeric arrays, strings, etc., this can be simple. For those that take other datatypes, more advanced tools like coder.opaque, coder.cstructname and custom enumeration definitions must be used which can take time. One needs to weigh the cost of developing this interface for MATLAB Coder versus learning and using the MATLAB libraries mentioned in the first bullet.
If you eventually want to use the code in C outside of MATLAB, with MATLAB Coder and coder.ceval, the target can simply be changed from MEX to a standalone target like a static or dynamic library or executable. With a handwritten MEX file, one typically factors the C code so that the MEX interface, mexFunction, is separate from the C functional kernel. Then, this kernel can be called outside of MEX. If you are planning to use MATLAB Coder anyway, you'll have to integrate the MATLAB Coder code with this kernel somehow.
If the code is to be used with MATLAB Coder eventually, calling MEX files using Coder when the target is MEX requires using coder.extrinsic. They also cannot be called directly in standalone targets. Instead, the C computational kernel underlying the MEX file needs to be integrated with the generated code either during code generation using coder.ceval or after code generating using a traditional C development environment.
Factors to Consider When Deciding
Do the benefits of integrating the C code early using MATLAB Coder and having the MEX interface auto-generated outweigh the work required to use the MATLAB Coder external code interfaces versus a hand-written MEX file?
Is integrating the external C code using coder.ceval easier or harder than writing a MEX file that exposes it to MATLAB and then later integrating your MATLAB Coder generated code with the computational kernel underlying your MEX file?

Call MATLAB function from a C program [duplicate]

I have some code that plots triangles in MATLAB.
I need to be able to somehow execute this code from my C program which generates these points.
Is that possible? How can it be done?
Just a thought:
Can I somehow embed MATLAB code in C, so that it can compile on a C compiler?
The Mathworks site has full details; a demo video of calling the Matlab engine from C, and also the Matlab to C Compiler.
As mentioned previously by answerers, you can call a live copy of MATLAB from C via the MATLAB Engine interface.
If the end-product needs to be used where there is no live copy of MATLAB, you can deploy the application using MATLAB Compiler. However, MATLAB Compiler does not, as another answer has suggested, convert MATLAB programs into C code (and hasn't done for a few versions now). Instead, it archives and encrypts your MATLAB program, and packages it into an executable or shared library that executes against the MATLAB Compiler Runtime (shareable royalty-free). The executable or shared library can then be called from C.
Alternatively you could go the other way around, and call your C code from MATLAB, using either loadlibrary or MATLAB's MEX interface.
Update: As of release R2011a, you can also use MATLAB Coder to generate C code directly from a subset of the MATLAB language.
Look at this presentation about integrating MATLAB Algorithms in C or C++ Applications http://www.mathworks.com/videos/integrating-matlab-algorithms-in-c-or-c-applications-86431.html

Turning strings into code?

So let's say I have a string containing some code in C, predictably read from a file that has other things in it besides normal C code. How would I turn this string into code usable by the program? Do I have to write an entire interpreter, or is there a library that already does this for me? The code in question may call subroutines that I declared in my actual C file, so one that only accounts for stock C commands may not work.
Whoo. With C this is actually pretty hard.
You've basically got a couple of options:
interpret the code
To do this, you'll hae to write an interpreter, and interpreting C is a fairly hard problem. There have been C interpreters available in the past, but I haven't read about one recently. In any case, unless you reallY really need this, writing your own interpreter is a big project.
Googling does show a couple of open-source (partial) C interpreters, like picoc
compile and dynamically load
If you can capture the code and wrap it so it makes a syntactically complete C source file, then you can compile it into a C dynamically loadable library: a DLL in Windows, or a .so in more variants of UNIX. Then you could load the result at runtime.
Now, what normally would lead someone to do this is a need to be able to express some complicated scripting functions. Have you considered the possibility of using a different language? Python, Scheme (guile) and Lua are easily available to add as a scripting language to a C application.
C has nothing of this nature. That's because C is compiled, and the compiler needs to do a lot of building of the code before the code starts running (hence receives a string as input) that it can't really change on the fly that easily. Compiled languages have a rigidity to them while interpreted languages have a flexibility.
You're thinking of Perl, Python PHP etc. and so called "fourth generation languages." I'm sure there's a technical term in c.s. for this flexibility, but C doesn't have it. You'll need to switch to one of these languages (and give up performance) if you have a task that requires this sort of string use much. Check out Perl's /e flag with regexes, for instance.
In C, you'll need to design your application so you don't need to do this. This is generally quite doable, as for its non-OO-ness and other deficiencies many huge, complex applications run on well-written C just fine.

matlab in C C++ and C C++ in matlab [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
It seems that are several ways to call matlab in C C++ and to call C C++ in matlab. While I try to list them here, please point it out If I miss something.
To call C C++ in matlab, there are also two methods. The first one is to call functions in C shared libraries. The second one is to build C C++ code into binary MEX-files, which will be called from the MATLAB command line. For the first method, are the C shared libraries are just general ones, i.e. without change to their C code for matlab and compiled from general C compiler like gcc?
To call matlab code in C C++, there are two methods available. The first one is Matlab engine. The second one is to use MATLAB Compiler mcc to create C or C++ shared libraries from your MATLAB code.
Besides matlab and C C++ can communicate via writing and reading data to and from some file (e.g. mat file, text file).
Having more than one ways to accomplish each of the goals here, could you tell me what cases are best for using which of them? i.e. calling functions in C shared libraries VS building C C++ code into binary MEX-files, Matlab engine VS compiling Matlab code into C C++ shared library.
Thanks and regards!
I only have expreience with calling C or C++ functions from MATLAB. It looks to me like the only difference between calling functions in a shared library and calling functions from a MEX file is that with a shared library, you have to call the function with 'calllib' which is a command line type function and MEX functions allow you to call functions as if they are built-in functions so the interface is a little cleaner.
My suggestion is to use MEX files if
You are using C++ (you may have to write a wrapper to use a C++ in a shared library)
You are using MATLAB as the glue for a large number of optimized C or C++ routines. You'll want to be able to call them cleanly.
Use shared library if
You already have an existing C library that can be used without modification.
You only need a small number of calls to C functions.
Really, it comes down to the interface. I personally prefer the MEX file route because it provides the cleanest interface from MATLAB to your C or C++ function. You can call it like just another function with standard MATLAB types. With a shared library, you may have to do some data formatting before calling the library function
I think the methods you've named are correct (it's been a while since I've used them)
The matlab C-compiler isn't really special; it is possible to use different compilers. See link list of supported compilers. This does not include gcc, but MS Visual studio is included. You'll run into issues when linking with the supplied libraries.
Basically: calling matlab from C is something you'd do if you need a tight interface; for instance if you want to synchronise 2 tools, or your S-function (simulink) requires additional information. But then, such a file is propably called by Matlab/simulink in the first place.
Calling c from matlab is what you want to do if you write your own S-functions or extensions to matlab.
The choice between C and C++ is yours; if you start from a blank sheet I suggest you use C++; you don't need to use the complete functionality but it allows more freedom. Also more libraries tend to be available for C++ nowadays.
C is the language of choice if you need to migrate to very different environments; i.e. to compile C to DSPs for instance. Or if you have got legacy code in C to start from. Mixing C and C++ is possible, but a can be a bit cumbersome; I'm sure you'll find topics on StackOverflow on this subject alone.

Resources