Use quadgk with multiple Inputs with Matlab Coder

8 views (last 30 days)
Hi I want to create a C file out of my Matlab file. In my Matab file I have to make some integrations, that is way I am using the quadgk function. My problem is now, that the Matlab Coder for generating the C Code doesn't allow function handels.
I want to integrate the function
function val=integrand1(x,c,d) val=x*c+d; end
by the follwing term
Integral = quadgk('integrand1',z(1),z(2),-1,z(2))
So the intergal goes from z(1) to z(2) and for the parameters c and d I want to use the values -1 and z(2). If I do so the Matlab Coder gives the errow ??? First input argument must be a function handle.
But how can I use quadgk instead? Thank you very much for any help.
Best regards Antonia

Accepted Answer

Mike Hosea
Mike Hosea on 20 Feb 2014
Edited: Mike Hosea on 20 Feb 2014
I don't have a lot of time to type this. Hopefully if it isn't clear I can come back and add some detail.
The way we normally do this in MATLAB is not with a string to represent the integrand. That is obsolete. The standard way would be integrate the anonymous function @(x)integrand1(x,c,d), where c and d would be defined before, e.g.
Unfortunately, this won't work in MATLAB Coder because MATLAB Coder doesn't support anonymous functions. So you will have to do something a little more complicated using persistent variables, something like
function val = integrand(x,c,d)
persistent c_saved,d_saved
if isempty(c_saved)
c_saved = 0;
d_saved = 0;
if nargin >= 2
c_saved = c;
if nargin >= 3
d_saved = d;
val = x*c_saved + d_saved;
Then to use it, you just call it first with your desired c and d.
integral = quadgk(@integrand1,z(1),z(2));
I apologize if I have made a typo or some other boneheaded error above. I don't have time to test it, but we test QUADGK for code generation using this basic approach, so I know it can work. -- Mike
Tunga Rangaswamy
Tunga Rangaswamy on 16 Oct 2019
Thanks Steven!
My question is also based on anonymous function and MATLAB coder which seemed aligned to the previous question. However, I have asked this a separate question now and I am looking forward to an answer.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!