- You use input('prompt text','s'), which is great. A very robust and healthy choice. Note that specifying the 's' option means that input returns a string.
- The line if (nargin >1) makes no sense, because nargin actually tell us how many input arguments there are to the function it is within, which in this case you have defined as ask_for_number(). Those parentheses are empty so there are exactly zero input arguments possible, and this boolean will therefore always be false. If you want to check that the user did not enter multiple numbers after the input prompt, then you need to use a different tool.
- The code inside the while loop does not change the loop variable valid_number, which is used to break the condition. So if the first number is negative it will never break out of this loop. Try it, and you be trapped forever in this loop.
- The line ~isnumeric(valid_number) does nothing useful at all, which you discover when you read the documentation for str2double: if str does not represent a valid scalarvalue, str2double returns NaN. Because NaN is numeric, this test will always be false, regardless of what characters the user enters.
- The line isempty(txt_input) & isnan(txt_input) also does nothing useful. If the user does not enter any characters or digits and simply presses enter after the input prompt then txt_input will be empty, so isempty(..) will be true. However as we noted in the very first point above, the function input returns a string, and isnan is a test for a numeric NaN value. Passing it any string, even 'NaN', will return false. So this line will never be true, and the code following it will never run.
- start again from an empty function.
- Use the documentation. The lovely people at MathWorks put it there for a reason, and the more you use it the more useful it becomes.
- write one line at a time, or some minimal amount for loops and the like.
- test each line after you write it. Use disp or the debugger, or whatever tool you feel comfortable with to check that the values are correct.
- Write down a list of test cases as you are writing your code. Every time you find a test case that you want your code to handle, ans also for every failure or special case, write it down. Use this list for testing your function.
- If you want to do something, and you are not sure how, look on the internet for answers and examples, look at the documentation (it has working examples!), and if that does not work, come back here and ask us.