I thought this one is interesting (Simulink)

4 views (last 30 days)
bethel o
bethel o on 7 Aug 2012
The two functions below are basically the same but the second one includes an else statement at the end. They are functions for matlab function block in simulink. The matlab function block gives error on the first one(regarding unset output in some execution path) but not in the second one even though the else statement on the second function is never needed. Should the compiler no better of is this acceptable? The input signal is shown below:
input signal:
u=256*10;
Averaging=256;
function y = fcn(u,Averaging)
%#codegen
persistent dwork1;
%coder.extrinsic('disp');
assert(Averaging<=256+1);
if(isempty(dwork1))
dwork1=zeros(Averaging+1,2);
dwork1(1)=1;
else
dwork1(1)=dwork1(1)+1;
end
avg2=2*Averaging;
if(dwork1(1)<=Averaging)
dwork1(dwork1(1)+1,1)=u(1);
y=-2;
elseif(dwork1(1)>Averaging && dwork1(1)<=avg2)
dwork1(dwork1(1)+1-Averaging,2)=u(1);
y=-1;
elseif(dwork1(1)>avg2)
%CAUTION: the input u is ignored here
dwork1(1)=Averaging+1;
d1=dwork1(2:end,2)-dwork1(2:end,1);
y=length(d1(d1<0));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = fcn(u,Averaging)
%#codegen
persistent dwork1;
%coder.extrinsic('disp');
assert(Averaging<=256+1);
if(isempty(dwork1))
dwork1=zeros(Averaging+1,2);
dwork1(1)=1;
else
dwork1(1)=dwork1(1)+1;
end
avg2=2*Averaging;
if(dwork1(1)<=Averaging)
dwork1(dwork1(1)+1,1)=u(1);
y=-2;
elseif(dwork1(1)>Averaging && dwork1(1)<=avg2)
dwork1(dwork1(1)+1-Averaging,2)=u(1);
y=-1;
elseif(dwork1(1)>avg2)
%CAUTION: the input u is ignored here
dwork1(1)=Averaging+1;
d1=dwork1(2:end,2)-dwork1(2:end,1);
y=length(d1(d1<0));
else
%CAUTION: this portion should never be executed, therefore y should
%never be equal to -10
y=-10;
%disp(dwork1(1))
end

Answers (1)

Walter Roberson
Walter Roberson on 8 Aug 2012
At the time of compilation, the routine does not know that Averaging cannot be NaN.
  1 Comment
bethel o
bethel o on 8 Aug 2012
hmm but let me be pedantic, the computer should probably let the programmer control stuff. The programmer is probabily wise enough to know that 'Averaging' can never be NaN and that was why he wrote his code like that. But the computer who does not know what 'Averaging' is thinks that the programmer is just a stupid human and that 'Averaging' can be NaN(how rebellious).
Actually the programmer of the first function wanted the programme to crash when 'y' was not set. But it seems it is impossible to crash the computer in this way not because the computer is incapable but because the computer thinks he knows better.
And by the way a C code written in that way would happily compile(obedient computer).

Sign in to comment.

Categories

Find more on Simulink Coder 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!