Skip to main content
Engineering LibreTexts

5.5: Functions With Multiple Input Variables

  • Page ID
    86183
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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 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; a detailed edit history is available upon request.