![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/802114/image.png)
Use of fminbnd in Simulink Matlab Function
4 次查看(过去 30 天)
显示 更早的评论
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?
I am really looking forward to your helpful comments!
0 个评论
回答(1 个)
Pavan Guntha
2021-11-16
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/802114/image.png)
Hope this helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulink Functions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!