Functions can take more than one input variable. For example, the following function in Listing 5.2 takes two input variables, a and b:
Listing 5.2: A function that computes the sum of squares of two numbers
function res = sum_squares(a, b)
res = a^2 + b^2;
end
This function computes the sum of squares of two numbers, a and b.
If we call it from the Command Window with arguments 3 and 4, we can confirm that the sum of their squares is 25.
>> ss = sum_squares(3, 4)
ss = 25
The arguments you provide are assigned to the input variables in order, so in this case 3 is assigned to a and 4 is assigned to b. MATLAB checks that you provide the right number of arguments; if you provide too few, you get
>> ss = sum_squares(3)
Not enough input arguments.
Error in sum_squares (line 4)
res = a^2 + b^2;
This error message might be confusing, because it suggests that the problem is in sum_squares rather than in the function call. Keep that in mind when you’re debugging.
If you provide too many arguments, you get
ss = sum_squares(3, 4, 5)
Error using sum_squares
Too many input arguments.
That’s a better error message, because it’s clear that the problem isn’t in the function, it’s in the way we’re using the function.