how to write mex function when input is a matlab function

1 view (last 30 days)
Yan WANG
Yan WANG on 23 Jan 2022
Answered: James Tursa on 25 Jan 2022
I want to write a C code to replace the fzero function in matlab by using MEX function, while the function's form is an input in the C code, how can I specify it?
Currently my C code is like following:
#include "mex.h"
#include <stdio.h>
#include <stdio.h>
#include <math.h>
// secant method
double f_zero(double(*f)(double x),double a,double b, double error)
{
double c;
int count=0;
if (f(a) * f(b)>0)
{
b = -b;
}
c = (b*f(a)-a*f(b))/(f(a)-f(b));;
while(fabs(f(c))>error && count <100)
{
count = count+1;
if (f(a)*f(c)<0)
{
b=c;
}
else
{
a=c;
}
c = (b*f(a)-a*f(b))/(f(a)-f(b));;
}
return c;
}
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
#define FCN_IN prhs[0]
#define x1 prhs[1]
#define x2 prhs[2]
#define x3 prhs[3]
#define Y_OUT plhs[0]
Y_OUT = f_zero(FCN_IN,x1,x2,x3);
}
suppose f = @(x) x*x + 3x-4;
how can I get f_zero_c(fun,-5,0,0.00001) in matlab?
Thanks a lot!

Answers (1)

James Tursa
James Tursa on 25 Jan 2022
This can be done, but it will not be efficient. The basic problem is that C/C++ doesn't understand anything about MATLAB functions. You would have to write a wrapper function with callbacks to accomplish this, and the overhead of doing this would hardly make the effort worh it IMO. C/C++ function pointers cannot point to MATLAB functions directly ... they have to use the mexCallMATLAB( ) API function. So input/output arguments must be copied to/from mxArray types to accomplish the function evaulation. I.e., every time you want to call your f( ) function you have to invoke the mexCallMATLAB( ) function in the background. I would advise that you first learn how to write simple mex functions (e.g., multiply a number by 2, or add two numbers together) before you tackle something like writing your own fzero( ) replacement.

Community Treasure Hunt

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

Start Hunting!