Simulink Error fzero must always return a real value

2 ビュー (過去 30 日間)
Florian Lüder
Florian Lüder 2021 年 9 月 18 日
回答済み: Pramil 2024 年 2 月 29 日
I want to use the function fzero in a Matlab Function Block in Simulink to find the zero of a function.
To be precise:
func = @(x) ((m^2+1)*x+m*n-yego*m-xego)/(sqrt((x-xego)^2+(m*x+n-yego)^2));
var = fzero (func, 1);
Whereas m, n, yego and xego are double variables, which are defined previous. In my case each of these variables can have four different double states.
If I try the code for every of the possibilities in Matlab Command Windows everything works fine and i get double values for var in every case.
Now if i try to run this code in a Matlab Function Block in Simulink I get the following error:
User function must always return a real value.
Function 'myFunction' (#24.3658.3684), line 101, column 13:
"fzero (func, 1)"
Launch diagnostic report.
Component: MATLAB Function | Category: Coder error
I just do not know, what to do with this error, because for every possible value for the parameters m, n, yego, xego, x and y i do get double values in Matlab, so the Variable var could not be of another type than real.
Thank your for your advices!

回答 (1 件)

Pramil
Pramil 2024 年 2 月 29 日
The error that you are getting is because at “x=1” for certain combinations of “m”,” n”,” xego” and “yego” the denominator of the function becomes zero. One such example is when “m = 1”,” n=1”,” xego=1” and “yego=2”.
What you can do is, first check the value of function at “x” by using “isnan” function and if the function value is “NaN”, which it will be when denominator becomes zero. You can set the output value of “MATLAB function” block to “inf” in this case or any other value you want. This will resolve the error.
Here is code snippet that works well inside the “MATLAB Function” block in MATLAB version R2021a:
function y = fcn(m,n,xego,yego,val)
func = @(x) ((m^2+1)*x+m*n-yego*m-xego)/(sqrt((x-xego)^2+(m*x+n-yego)^2));
temp = func(val);
if isnan(temp)
y = inf;
else
y = fzero (func, 1);
end
end
You can also refer to this MATLAB answer for knowing more about this error with respect to “fzero” function:

カテゴリ

Help Center および File ExchangeSimulink Coder についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by