I have encountered a strange behavior while solving one of the problems in Cody. I have simplified the code into the following
function ans = junk(s)try s;catch 999end
This code gives an error if an output is requested (a=junk(3)), i.e it does not assign s to ans (it does not throw an error, though, within the try block, so adding the catch block has no effect).
The strange part is that if the semicolon is removed or replaced with a comma, it works correctly. Also, if any operation is performed on s (e.g. s+0) it works fine.
If the variable (ans) is invoked within the try block on a separate line after s, it works fine. Strange again, if (ans) is added on the same line as s with a semicolon or a comma, it jumps to the catch block, confirming no assignment in the semicolon case, but not for the comma case which worked fine before.
Any suggestions what causes this behavior? Am I missing something?
UPDATE:
Trying to avoid the try-catch block I tried a switch statement. I encountered further strange behavior of the 'ans' variable. Consider:
function ans = kkk(f,a)switch nargin case 1 f; otherwise 999;end
This time a=kkk(1) works fine, but when the input is a function handle it errors out
>> a=kkk(1)
a =
1
>> a=kkk(@plus)
Error in kkk (line 2)
switch nargin
Output argument "ans" (and maybe others) not assigned during call to "C:\Users\Dr. K. Hamed\Documents\MATLAB\kkk.m>kkk".
Best Answer