Use of fminbnd in Simulink Matlab Function

4 views (last 30 days)
Florian Lüder on 17 Sep 2021
Answered: Pavan Guntha on 16 Nov 2021
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:
myFunc.m
function [xloc,dis] = funcmin(fun,xlow,xup)
[xloc, dis] = fminbnd(fun, xlow, xup);
end
In the Matlab Function Block
coder.extrinsic('funcmin');
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:
"fun"
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?

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);
end
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.
coder.extrinsic("fcn")
% 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!

R2021a

Community Treasure Hunt

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

Start Hunting!