Use of fminbnd in Simulink Matlab Function

13 views (last 30 days)
Hi folks!
I have a project, in which I have to use a Matlab Function Block within Simulink. I really would like to use the anonymous function fminbnd to find a minimum of a function within a given interval.
In Matlab this is quite easy. In my specific case the variables xego, yego, m, n, xlow and xup are variable, which are defined in the Matlab Function Block in Simulink.
fun = @(x) sqrt((x-xego)^2+(m*x+n-yego)^2);
[xloc, dis] = fminbnd(fun,xlow,xup);
Now it seems that R2021a does not support fminbnd in a Simulink Function Block, but I need a possibility to find the minimum of a function with function parameters which are defined within the matlab function block.
I do have read about the possibility to call fminbnd as extrinsic function and i tried this with the following code:
function [xloc,dis] = funcmin(fun,xlow,xup)
[xloc, dis] = fminbnd(fun, xlow, xup);
In the Matlab Function Block
xloc = 0;
dis = 0;
[xloc, dis] = funcmin (fun, xlow, xup);
But if i try to run the Simulink model i get the following error text
Function handles cannot be passed to extrinsic functions.
Function 'Lokalisierung' (#24.3039.3042), line 92, column 28:
Launch diagnostic report.
Component: MATLAB Function | Category: Coder error
What is my mistake in this case? Is my idea of handling the parameters to the extrinsic function wrong?
I am really looking forward to your helpful comments!

Answers (1)

Pavan Guntha
Pavan Guntha on 16 Nov 2021
Hello Florian,
You could follow the following steps to use fminbnd function within a Simulink model:
1) Create a MATLAB function 'fcn.m' file which has the following logic:
function [xloc, dis] = fcn(xlow, xup)
fun = @(x) sqrt((x-1)^2+(1*x+1-0.5)^2);
[xloc, dis] = fminbnd(fun,xlow,xup);
2) Create a Simulink model and place the MATLAB function block which takes 'xlow' and 'xup' as input parameters and gives out 'xloc' and 'dis' as output parameters.
function [xloc, dis] = func(xlow, xup)
% Exclude code generation for 'fcn' which internally has 'fminbnd' which doesn't support codegen.
% Initialization of Output parameters is necessary to avoid data type
% related issues.
xloc = 0;
dis = 0;
[xloc, dis] = fcn(xlow, xup);
The Simulink model looks as follows:
For more information on coder.extrinsic, you could look at the documentation page here.
Hope this helps!


Find more on Simulink Functions 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!