MATLAB: Does function create ‘ans’ output when it is already assigned

functionoutput

a code i've done for my assignment, except upon choosing '0' to exit the while loop, the function creates an 'ans' variable which is unwarranted.
If the entire code is ran inside a script, this does not occur. How may i suppress this? Unless i'm missing something obvious i am puzzled how this is happening. Thank you
Edit: Actual code removed once problem was fixed to avoid future plagiarising of assignment

Best Answer

There are actually two cases where you'll get a ans = display.
The first one is simply caused by the way you call your function, if you do:
>>rps
then when the function ends, you'll get a display of the return value, winner since you haven't terminated the call with a semicolon. This is what happens in the screenshot you showed. To fix that, it's simple, terminate the function call with a semicolon. This has nothing to do with the function code itself:
>>rps; %won't display ans when the function terminates
The second problem is more subtle. In the code, you have:
while player_move ~0
Because of the typo, this is equivalent to:
while player_move
~0 %statement not terminated by a colon, so outputs the result of ~0, which is 1
You of course meant to have
while player_move ~= 0
Note that matlab editors actually highlights the ~ and tells you that there are two problems with the above line. As a rule, if the editor highlights something, you should investigate and fix the issue. It's usually because you've made a mistake.
The other critical section which the editor highlights is your
else winner == 0;
which again does not do what you meant. It's equivalent to:
else
winner == 0; %does not do anything. would have display 0 or 1 if not terminated by a semicolon.
Morale of the story: make sure that there is nothing highlighted in your code.
Related Question