Simulink Error fzero must always return a real value

1 visualizzazione (ultimi 30 giorni)
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!

Risposte (1)

Pramil
Pramil il 29 Feb 2024
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:

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by