Making a mex function for a rather complex code
Show older comments
Hello friends,
I have a code which is very time consumming. Therefore, I thought to use mex function to do the heavy part of calculations using C or C++. I have difficulty to define input types properly as my code has some inputs which are rather complex, for instance one input is a function handle and the other one is a variable sized cell whose elements are function handles. The rest of inputs are easy.
To make things easier I thought to ask my question via a very simple code (attached as main.m) rather than mine (this code does nothing for me but if I understand how to tackle this code I am able to tackle my own code). In this code there is a subrutine called 'Cost' which is the 'heay part'. I would like to make a mex function for this subrutine to speed up the calculations. Please note that this code is not my real code and I just made it for the purpose of learning how to make a mex file out of this code (I know that this code does not solve any scientific problem).
I impatiently look forward to hearing from you soon,
Thanks in advance!
Babak
3 Comments
Mohammad Shojaei Arani
on 5 Jul 2022
Jan
on 5 Jul 2022
As far as I understand, you post a simplified code which differs from the real code. This is a usual cause of not helpful answers, because the actual problm can be hidden in the concealed code.
Symbolic variables and function handles do not profit frem mexing, because the mex function have to call Matlab to evaluate the expressions.
Use the profiler to find the bottleneck of the real code. Post the results together with the real code. Then an efficient help is possible and the time spent fpr typing the answer will less likely be lost.
Mohammad Shojaei Arani
on 5 Jul 2022
Edited: Jan
on 5 Jul 2022
Answers (1)
Varun
on 25 Oct 2023
0 votes
Hi Shojaei,
Looks like you want to have a mex function in C/C++ for the MATLAB subroutine "Cost". There are total 5 input arguments to the "Cost" function out of which "par", "data" and "J" are simple input arguments while "H" is a function handle and "Coeff" is a variable sized cell whose elements are function handles.
You can pass function handles to your C++ MEX files as usual and then use “mexCallMatlab” function in C++ code to execute the function handles using the "feval" command. Please refer to the following post for more information:
Also refer the following MATLAB documentation to learn more about "mexCallMatlab" and "feval":
"mexCallMatlab":
"feval":
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!