Reputation: 3675
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?
Upvotes: 2
Views: 254
Reputation: 3033
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.
Upvotes: 1
Reputation: 11181
Yes, Matlab has a C/C++ API.
This API permits to:
.mat
fileI am working to something similar to what you are trying to do, my approach is:
.mat
file.mat
fileThe 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.
Upvotes: 3
Reputation: 78306
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.
Upvotes: 4