Search code examples
matlabif-statementoutputmatlab-compiler

If statement MATLAB example issue


I'm trying to run this simple if-statement MATLAB code on MATLAB 7.6.0 (R2008a) version.

*I typed this in M-File:

function output = DEMO(input)
 if input > 0
   fprintf('Greater than 0')
elseif input < 0
   fprintf('Less then 0')
else
   fprintf('Equals 0')
end

outvar = 1;

*Tried to implement it in command window: Whenever I entered a number it always gives me Greater than 0!

As here: enter image description here

What's wrong? I could not figure it out? Is it because the outvar = 1? I tried to make it 0, got the same result! -.-


Solution

  • When you call a function the following way:

    DEMO 0
    

    This implicitly passes 0 as a string: '0'. When you perform a comparison between the string '0' and 0, the '0' is converted to it's ASCII code (32) and it always appears to be greater than 0.

    Instead, you will want to use parentheses to explicitly call the function and pass a number.

    DEMO(0)
    

    As a side note, you seem to be assigning to outvar but then the output argument of your function is actually output. Also, you assign outvar to 1 at the bottom regardless of the condition. If you want a different output value for each condition, you need to set the output value within the if statement of interest.

    Maybe something like:

    function output = DEMO(input)
        if input > 0
           fprintf('Greater than 0')
           output = 1;
        elseif input < 0
           fprintf('Less then 0')
           output = -1;
        else
           fprintf('Equals 0')
           output = 0;
        end
    end