Making a mex function for a rather complex code

2 views (last 30 days)
Mohammad Shojaei Arani
Mohammad Shojaei Arani on 4 Jul 2022
Edited: Jan on 5 Jul 2022
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
Mohammad Shojaei Arani on 5 Jul 2022
Hello Jan,
Thanks for your kind response and attention!
Well, if I wanted to post my actual problem that would be really big with lots of heavy math. So, I thought to make a very tiny and short problem which is not boring for you. I do not have any symbolic calculations inside my procedure but I do have function handles. You do not need to know the philosophy behind my code, my question should be extremely simple for highly experienced people that you really are. So, perhaps I can explain a bit further. In bellow, you see my code. My question is only related to the part being highlighted in bold (i.e., the function called Cost). I just want this part to be mexed and be done using C. To be more clear, I just need to know how to define type inputs in the matlab coder. For instance the input H is an anonymos function and I do not know how to define its type in matlab coder box. I If you teach me how to do this then I am done!
Thanks Jan, in advance!
clc;
data=rand(1,10);
J=5;
syms x
H=sym('H',[J 1]);
for j=1:J
H(j)=horner(simplify(exp(x^2/2)*diff(exp(-x^2/2),j)),x);
end
H=matlabFunction(H);
syms w
Coeff=cell(1,J);
for j=1:J
A=zeros(1,j+1);
for k=1:j+1
A(k)=(-1)^(k-1)*nchoosek(j,k-1);
end
C=A.* w.^(0:j);C=C(2:end);
Coeff{j}=matlabFunction(C);
end
cost=@(par)Cost(par,data,J,Coeff,H);
par=rand(1,J);
f=Cost(par,data,J,Coeff,H);
function cost=Cost(par,data,J,Coeff,H)
A=par*H(data);
B=0;
for j=1:J
C=Coeff{j}(par.');
B=B+norm(C);
end
cost=norm(A)+B;
end

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!