This is not an error. It is a failure of your code to work as it is supposed to work by your goals.
What did I say? What has EVERYONE said so far? You cannot set a default as you did.
Even though you pass in the number 18 as the limit, the first thing you do inside is reset that value to 21.
Instead, you need to think about how to test to see if limit was provided at all.
Edit: (18 months later)
Now that there are dozens of answers, all of which are lengthy, I'll show how I would write it.
function tooyoung = under_age(age,limit)
if nargin < 2, limit = 21; end
See that most of my code was actually comments. Help is hugely important, since it allows you to quickly use the code next year when you forget how it was written, or when you forget what the arguments mean.
Think of internal comments as reminders to yourself, for a year from now when you look at the code and need to change the code for some reason, or god forbid, you need to debug it. My recommended target is one line of comment per line of code, or at worst, one line of code per significant thing done in the code.
Comments are free! Good code should look positively green due to all of the comments. My solution code was lengthy only because of all of the comments.
What else?
Remember that white space is hugely important. It makes your code easy to read.
Use intelligent, meaningful variable names. Good mnemonic variable names help to make your code self-documenting, and again, easy to read. When you are scanning through the code, you don't want to continuously go back and be forced to remember what does the variable wxxyy do?
As I said, better code would have included tests to verify that both age and limit, if provided, were actually numeric variables. The best code is friendly code. When it fails, you want the code to fial in a friendly way, telling the person what was seen to be wrong. What you don't want to happen is the code does something screwy and unexpected, or returns some random difficult to understand error message. The best code makes it easy to use that code.
The final test in this code is a vectorized test, in that if you called the code like this:
tooyoung = under_age([12 5 29 75],21)
it will work and return a vector of results. Vectorized code is generally good code, since it allows the user to not be forced to use a loop when they want to use the code many times in a row.
Finally, could I have written code that would have required only one line of code? Thus testing to see if limit was provided, and returning a comparison to age in just one line? Probably, but that would have been unnecessarily complicated, difficult to read and debug. There would have been no gain in the quality of the code or how fast it runs. Good code is simple, easy to read, easy to use, easy to debug.
Best Answer