5.5: Functions With Multiple Input Variables

Matlab and Octave Programming for STEM Applications · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    5.5: Functions With Multiple Input Variables

    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.


    This page titled 5.5: Functions With Multiple Input Variables was last modified on Wed, 13 Jul 2022 23:48:18 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.