how use fzero with matlab coder and a function with parameters ?

2 visualizzazioni (ultimi 30 giorni)
I want to solve the equation f(x,p) = 0 for several values of p.
A correct way to perform this task is to write a function (here called findzero):
function y = findzero(p)
n = length(p);
y = zeros(1,n);
hf = @f;
for il=1:n
y(il) = fzero(@(x) hf(x,p(il)),0);
end
end
function out=f(x,p)
out = x-p;
end
unfortunately, when I try to generate the C code of findzero with matlab coder, I encounter the following error : findzero, line 6, "anonymous functions are not supported for code generation"
How can I modify findzero in order to successfully pass it in matlab coder ?

Risposte (1)

Ryan Livingston
Ryan Livingston il 24 Giu 2016
The typical workaround is to model an anonymous function using a sub-function with persistent variables to store the extra parameters. In your case, this function, let's reuse your f, would have the persistent p. Then, you make a call to f with 2 arguments to "set" the parameter right before the call to fzero:
% Set parameter value
f(0,p(il));
% Find root
fzero(@subfcn,0);
This answer gives an example in more detail which shows how to implement f.

Community Treasure Hunt

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

Start Hunting!

Translated by