2.5: Getting Input from the User

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

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

    2.5: Getting Input from the User

    So far, the width and height were written directly inside the script. That is called hard-coding values. Hard-coding is sometimes useful for quick testing, but it makes the program less flexible.

    A better version of the rectangle-area script asks the user to enter the width and height when the script runs. In MATLAB, this is done with the input function.


    Example \(\PageIndex{1}\)
    width = input('Please enter a value for the width of the rectangle: ');
    height = input('Please enter a value for the height of the rectangle: ');
    area = width * height.
    Solution
    If the user enters 3 for the width and 4 for the height, the area will be calculated as 12.

    When MATLAB reaches an input statement, it displays the prompt and waits. The user types a value and presses Enter. MATLAB then stores that value in the variable on the left side of the assignment statement.

    Numeric Input

    For numeric input, the user can type a number such as 4, 3.5, or 10. MATLAB reads the value and stores it as a numeric variable.

    Example \(\PageIndex{2}\)
    radius = input('Enter the radius: ');
    Solution
    Enter the radius:

    Text Input

    If the user is expected to enter text, add a lower case 's' or "s" as the second argument to input. This tells MATLAB to store the user response as text instead of trying to evaluate it as a variable or expression.

    Example \(\PageIndex{3}\)
    name = input('Please enter your name: ', 's');
    course = input('Please enter your course name: ', "s");
    Note

    Common mistake: If you forget the s for text input, MATLAB may try to interpret the entered word as a variable name. Always use input(prompt, s) when asking for a name, word, label, or sentence.


    This page titled 2.5: Getting Input from the User was last modified on Tue, 30 Jun 2026 02:11:44 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.