MATLAB .m file to .mex file using Matlab Compiler - c++

I know it could souds as a very famous topic, but I didn't find anything that helps me with this.
This is the scenario:
I have a myFun.m function, no matter what's inside, it is a generic function which could potentially depends on other toolboxes. It has inputs and outputs;
I want to generate the analogous myFun.mex function;
I have Matlab Compiler and I can compile myFun.m as
mcc -v -W lib:libmyFun -T link:lib myFun
In this way I get some new files:
libmyfun.c
libmyfun.dll
libmyfun.exp
libmyfun.exports
libmyfun.h
libmyfun.lib
Reading around and following Loren's example I guess I have to create a myfun.cpp which inside includes the very famous gateway function:
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* variable declarations here */
/* code here */
}
I've tried to do that and called the mex generation routine:
mex('-v', 'myfun.cpp')
but I get several errors, and I must say my myfun.cpp is copy/paste function where I have a lot of doubts on... especially on inputs/outputs management.
My question is... apart from the myfun.cpp function which could be full of errors as I'm not a C/C++ developer... is the process correct?
If the answer is YES, does anybody knows which is the generic way to write the myfun.cpp?
Cheers,
Sebastian

MATLAB Compiler does not do what you want.
MATLAB Compiler takes your .m code and encrypts and archives it into a .ctf (Component Technology File) file. It then produces a thin wrapper (either a .exe file, or a .dll library file along with files to enable calling the library from C). You deliver the .ctf file and the wrapper to your end user along with the freely redistributable MCR (MATLAB Compiler Runtime). It's possible to package either the first two or all three into a single unit for easier distribution.
The end user runs the executable or library, which dearchives and decrypts the .m code and runs it against the MCR rather than MATLAB. You can think of the MCR as basically a copy of MATLAB, but without the front-end desktop environment.
MATLAB Compiler is intended for the use case that you want to easily share a MATLAB application or algorithm with someone who does not have MATLAB. Because the code is encrypted, you can also use it to protect your intellectual property. But the code remains as .m code, and executes exactly as it would within MATLAB, including the same speed.
MEX is something different entirely. If you have an algorithm implemented in C code, you can add the 'gateway' routine you mention to it, and compile it with the command mex into a library that is then callable from MATLAB as if it were a regular MATLAB command or function. MEX functionality is part of regular MATLAB, and doesn't require any add-on products.
There is also another product, MATLAB Coder, that is distinct from MATLAB Compiler.
MATLAB Coder takes .m code that is in a subset of the MATLAB language, and converts it to C code. The subset is very extensive, but there are a few significant restrictions on the parts of the MATLAB language that are supported. I'm afraid those restrictions include many toolbox functions, including some functionality from Neural Networks Toolbox.
You can then do lots of things with that C code, including using MEX to compile it back into a form usable as a MATLAB command. This can often, though not always, provide a significant speedup over the original .m code. You can also do other things such as integrate the C code into a wider C project. or deliver it to an embedded device.
The main answer to your question is:
MATLAB Compiler doesn't do what you need.
To produce a MEX file file from your .m code, either recode it manually into C and then mex it, or use MATLAB Coder to automatically produce C code and then mex it.

Related

C++ and Matlab combination

I am writing a simulation of some differential equation. My idea was the following:
1. Write the core simulation (moving forward in time, takes a lot of time) in C++
2. Do initialisation and the analysis of the results with a program
like Matlab/Scilab
The reason for (1) is that C++ is faster if implemented correctly.
The reason for (2) is that for me it is easier to make analysis, like plotting etc..., with a program like Matlab.
Is it possible to do it like this, how do I call C++ from Matlab?
Or do you have some suggestions to do it in a different way?
You could certainly do as you suggest. But I suggest instead that you start by developing your entire solution in Matlab and only then, if its performance is genuinely holding your work back, consider translating key elements into C++. This will optimise the use of your time, possibly at the cost of your computer's time. But a computer is a modern donkey without a humane society to intervene when you flog it to death.
As you suggest, well written C++ can be expected to be faster than interpreted Matlab. But ask yourself What is Matlab written in ? For much of its computationally-intensive core functionality Matlab calls libraries written in C++ (or whatever). Your task would be not to write code faster than interpreted Matlab, but faster than C++ (or whatever) written by specialists urged on by a huge market of installed software.
Yes, Matlab has a C/C++ API.
This API permits to:
Write C++ functions which can be invoked from Matlab
Read/Write data from a .mat file
Invoke the Matlab engine from C++
I am working to something similar to what you are trying to do, my approach is:
Import in C++ the input data from a .mat file
Run the simulation
Export the results back in a .mat file
The Matlab API is in C, and I suggest you to write a C++ wrapper for your convenience.
In order to work with Matlab mxArray, I suggest to take a look at the boost::multi_array library.
In particular you can initialize an object of type multi_array_ref from a Matlab mxArray like this:
boost::multi_array_ref<double,2> vec ( mxGetPr (p), boost::extents[10][10], boost::fortran_storage_order() );
This approach made the code much more readable.
You can call your own C, C++, or Fortran subroutines from the MATLAB command line as if they were built-in functions. These programs, called binary MEX-files, are dynamically-linked subroutines that the MATLAB interpreter loads and executes.
You should set compiler, look here Setting up mex to use the Visual Studio 2010 compiler.
All about MEX-files here: http://www.mathworks.com/help/matlab/matlab_external/using-mex-files-to-call-c-c-and-fortran-programs.html.

import function Matlab Coder and C++ executable

Is there any work around for using the "import" function when coverting a matlab *.m file to a C++ executable?
Matlab gives me this response: "Import statements are currently unsupported." and I just wanted to know if I was SOL or not.
Thanks
import makes Java classes available to Matlab programs. Since doing so makes it necessary to actually have a running Java Runtime Environment, I think it would be very costly to provide this functionality to generated C++ code – while it is always present when running the original m-file. I therefore would interpret the error message to say exactly what it says: "unsupported".
To be more precise and give references: MATLAB Language Features Supported for C/C++ Code Generation explicitly says that Java is not supported, but Matlab classes are. Moreover, import is not contained in the list of Functions Supported for C/C++ Code Generation.

Matlab to C++ code generation (hdf5 format)

There is a Matlab function (h5write) that lets the user write output files in hdf5 format. This seems to work nicely when using the Matlab environment and Matlab files. However, when I try to generate C++ code out of the Matlab files, a conversion error arises. It appears that the code generator (Matlab Coder) cannot convert the h5write operation into C++ code.
Is there any way of getting around this issue? Efficiency is also important here since the data sets that need to be stored by the generated C++ executable are fairly large. If anybody could help me out here, it would make my day! :-)
MATLAB currently provide an interface for converting the code for h5write into C++ code. That being said, you can use MATLAB compiler to build an executable or dll. You can use this in your C++ code, but you will always need the MCR. If space is not a constraint, you can do this.
Otherwise, you can use the HDF5 API (http://www.hdfgroup.org/HDF5/doc/cpplus_RM/) and write code for writing into HDF5 file format and then use MATLAB Coder to link and compile.

Is it possible to convert mex code to C++ code?

I have written some mex (c++) code, i have used mxArrays, and few other Matlab functions, i am wondering is it possible to convert it to C++ code easily by including the appropriate header and making some minor changes ?
edit:
By "convert", i mean that i want to compile and run my code without relying (using) on matlab.
As mentioned in the comments above, making this work depends greatly on the nature of the MATLAB functions you are using. Since you have successfully ported much of your MATLAB code to C++, I suggest you continue doing so until you are no longer reliant on the MATLAB libraries to build.
Are there any toolbox functions you are relying on? If so this may be a bigger task than you realize.
Good luck!
You can make executable by using SimulinkCoder - so you can run it without Matlab ... but you still must use Matlab to make executable every time you make change in the code.
Make basic Simulink model with single S-function block in which you specify your mex file.
Use SimulinkCoder (Real Time Workshop) to make executable out of the Simulink model.

MATLAB arbitrary code execution

I am writing an automatic grader program under linux. There are several graders written in MATLAB, so I want to tie them all together and let students run a program to do an assignment, and have them choose the assignment. I am using a C++ main program, which then has mcc-compiled MATLAB libraries linked to it.
Specifically, my program reads a config file for the names of the various matlab programs, and other information. It then uses that information to present choices to the student. So, If an assignment changes, is added or removed, then all you have to do is change the config file.
The idea is that next, the program invokes the correct matlab library that has been compiled with mcc. But, that means that the libraries have to be recompiled if a grader gets changed. Worse, the whole program must be recompiled if a grader is added or removed. So, I would like one, simple, unchanging matlab library function to call the grader m-files directly. I currently have such a library, that uses eval on a string passed to it from the main program.
The problem is that when I do this, apparently, mcc absorbs the grader m-code into itself; changing the grader m code after compilation has no effect. I would like for this not to happen. It was brought to my attention that Mathworks may not want me to be able to do this, since it could bypass matlab entirely. That is not my intention, and I would be happy with a solution that requires a full matlab install.
My possible solutions are to use a mex file for the main program, or have the main program call a mcc library, which then calls a mex file, which then calls the proper grader. The reason I am hesitant about the first solution is that I'm not sure how many changes I would have to make to my code to make it work; my code is C++, not C, which I think makes things more complicated. The 2nd solution, though, may just be more complicated and ultimately have the same problem.
So, any thoughts on this situation? How should I do this?
You seem to have picked the most complicated way of solving the problem. Here are some alternatives:
Don't use C/C++ at all -- Write a MATLAB program to display the menu of choices (either a GUI for a simple text menu in the MATLAB command window) and then invoke the appropriate MATLAB grading programs.
Write your menu program in C/C++, but invoke MATLAB using a -r argument to run a specific grading program (to speed up the startup times, use the -nodesktop, -nojvm or -nodisplay options as appropriate). However, note that MATLAB will be started anew on each menu selection.
Write your menu program in C/C++ and start MATLAB using the popen command (this sets up a pipe between your C++ program and the MATLAB process). After a menu selection by the user:
your C++ program writes the name of the MATLAB program (and any parameters) to the pipe.
On the MATLAB side, write a MATLAB program to a blocking read on that pipe. When it reads a command, it invokes the appropriate MATLAB function.
You could also use named pipes. See this MATLAB newsgroup thread for more information.
Update: Option #3 above is effectively how the MATLAB engine works, so you are probably better off using that directly.
Don't make this a mex function.
Use a regular m-file that has to be executed in matlab. If you don't want to launch matlab first, write a bat file. I believe -r or -m runs a given command (you will have to cd to the correct directory before running you ml function).
To compile c++ code using mex first install visual studio. Then run (in matlab) mex -setup. Select "locate installed compilers" or some such, and then select your compiler from the list. Now mex will compile c++ code.
Using the MATLAB Engine to Call MATLAB Software from C/C++ and Fortran Programs