Why does my model fail using ELSEIF in an Embedded MATLAB Function Block in Simulink 6.1(R14SP1)?
2 views (last 30 days)
Show older comments
My model does not work if I use ELSEIF in an Embedded MATLAB Function Block in Simulink 6.1(R14SP1). The code in my Embedded MATLAB Function Block is below:
function y = fcn(u)
% This block supports an embeddable subset of the MATLAB language.
% See the help menu for details.
if (u<0)
x = 1;
elseif (u>=0)
x = 2;
end
y = x/2;
When I try to run my model, I get the following error:
Variable x must be unambiguously written to before use.
Accepted Answer
MathWorks Support Team
on 27 Jun 2009
We have verified that this is an intended behavior in Simulink. The reason for the error is that when compiling the Embedded MATLAB Function Block, Simulink must be able to ascertain a value for x before it is used to calculate y. In this case, even though the programmer knows that either the IF or ELSEIF clause must be executed, Simulink does not check the conditional statements to see if there is a certainty of entering one or the other. Instead, Simulink recognizes that in general, when there is an IF/ELSEIF without a final ELSE, there is no guarantee of any execution, and thus it is not guaranteed that x will be defined. Here are two workarounds:
1. Define x before the IF/ELSEIF statements as follows:
function y = fcn(u)
% This block supports an embeddable subset of the MATLAB language.
% See the help menu for details.
x = 0;
if (u<0)
x = 1;
elseif (u>=0)
x = 2;
end
y = x/2;
2. Use ELSE instead of ELSEIF for the last clause:
function y = fcn(u)
% This block supports an embeddable subset of the MATLAB language.
% See the help menu for details.
if (u<0)
x = 1;
else (u>=0)
x = 2;
end
y = x/2;
0 Comments
More Answers (0)
See Also
Categories
Find more on Simulink Environment Customization 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!