Problem 44397. Determine whether the input is odd, even, or neither.
Solution Stats
Problem Comments
Solution Comments
-
2 Comments
This solution probably doesn't work well for single character inputs though. (For example, when x = 'A'.)
Yeah, i've added said solution to the test suite as the question could include any input
-
8 Comments
Why does this not work (while Solution 1328031 does work)?
Because a comma separated list cannot be assigned to a single variable, this is how your previous solution catched the assignment error and triggered the catch statement (as desired). However, what you did here is only to generate a comma separated list without any assignment, and thus, no assignment error occurs which cannot trigger the catch statement.
Thanks, Peng Liu, for your concise explanation! It greatly helps in improving my understanding of cell variables/comma-separated lists as well as the try-catch function and error handling, which are topics that I still find quite complicated; but your comment explains it very clearly and easily! :-)
However, on closer inspection, I feel there's still something missing in the explanation. If it's merely a matter of failed/absent variable assignment to a comma-separated list, then why does this code still successfully enter into the catch statement in tests #3 and #6 (in which input x is a non-integer number)?
For the non-integer test cases #3 and #6, it is the subscript indexing error that was catched in your ans{index} indexing statement (because subscript index has to be either positive integer or logical).
But in tests #7 and #8 too, the subscript index is neither a positive integer nor a logical value; so why does it not lead to the same subscript indexing error that invokes the 'catch' statement?
Tests #7 and 8 involved an 0*0 array [] as the index, which is an extreme case where MATLAB returns nothing without issuing any error. Since no error occurs in the try block, the program flow does not enter the catch block. Hope this helps.
Thanks, Peng Liu! I would have expected that [] as an index of a cell variable would lead to an error, but apparently MATLAB accepts it and produces a comma-separated list of zero terms (which I now realize is apparently different from an empty matrix, otherwise it would have assigned "ans = [];"). Anyway, again, thanks for your comments, it really helped me understanding MATLAB better!
Problem Recent Solvers46
Suggested Problems
-
292 Solvers
-
Create an index-powered vector
561 Solvers
-
301 Solvers
-
166 Solvers
-
1196 Solvers
More from this Author1
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!