Table of Contents
Asking the User for Input
In many automation and scripting tasks you will not want to hard code every value. Instead, you can ask the user to type information when the script runs. MATLAB provides the function input for this purpose.
The simplest way to use input is to provide a prompt, which is the text MATLAB shows in the Command Window to tell the user what to type. For example:
age = input('Enter your age: ');
When this line executes, MATLAB prints Enter your age: in the Command Window and waits. The user types something and presses Enter. The value they type is returned by input and stored in the variable age.
By default, input interprets what the user types as a MATLAB expression. If the user types 10+5, age will be set to 15. If the user types a vector like [1 2 3], then age becomes a numeric array. If the user types something that is not a valid MATLAB expression, MATLAB will produce an error and the script will stop at that line.
Because input treats input as an expression, it is naturally suitable for numeric values. For text input, MATLAB uses a second form of input that returns a string rather than evaluating the expression, which is described later in this chapter.
You can combine input with other operations in a script. For example:
radius = input('Enter circle radius: ');
area = pi * radius.^2;
disp(area);Here the script asks for a radius, computes an area, and displays the result, all based on what the user typed.
Controlling How Input Is Evaluated
When you use input with one argument, MATLAB evaluates the user input as code. In some situations this is not what you want. If the user should type text such as a name, a yes or no answer, or any nonnumeric code, you should prevent MATLAB from trying to evaluate it as an expression.
To obtain literal text, call input with a second argument, 's'. In this case input returns a character vector containing exactly what the user typed, without evaluation. For example:
name = input('What is your name? ', 's');
If the user types Alice, the variable name contains the characters A, l, i, c, e. MATLAB does not try to interpret Alice as a variable or expression.
Using the 's' option is also useful when you want to read input like y or n, file names, codes that include letters and digits, or any value where mathematical interpretation is not intended.
The choice between evaluated input and string input is important. If you expect a number, the basic form:
value = input('Enter a number: ');
is convenient, because the result is already numeric. If you expect text, or you want to later process user responses as strings, the form with 's' avoids evaluation and potential errors.
Displaying Messages with disp
In simple scripts that interact with the user, you often need to show information and results. MATLAB provides several ways to display output, and the simplest is the function disp.
The disp function takes a value and prints a simple, readable representation in the Command Window, followed by a new line. Unlike lower level printing functions, disp does not show the variable name and does not require format strings. For example:
x = 42;
disp(x);prints just:
42
You can also use disp to show text. If you give disp a character vector or string, it prints that text exactly. For instance:
disp('Computation finished.');
writes Computation finished. to the Command Window.
One important detail is that disp accepts a single argument. If you want to combine text and numbers, you need to build one combined value before calling disp. An easy approach for text plus small numbers is to convert the number to text, then concatenate. For example:
name = 'Alice';
score = 95;
msg = ['Student ', name, ' scored ', num2str(score)];
disp(msg);
Here num2str converts the numeric score to characters, so it can be joined with the surrounding text. There are more advanced ways to format output, but for simple interaction disp plus basic string operations are usually enough.
Simple Question and Answer Scripts
By combining input and disp, you can create small interactive scripts that ask questions and respond based on the answers. This is often useful to make automation scripts flexible without editing the code each time.
For example, a short script can ask for a name and an age, then display a message that uses both values:
name = input('Enter your name: ', 's');
age = input('Enter your age: ');
disp(' ');
disp('Summary:');
disp(['Name: ', name]);
disp(['Age: ', num2str(age)]);
When this script runs, the user sees prompts for name and age. After typing, the script prints a small summary. The blank disp(' '); call inserts an empty line to separate parts of the output.
Another script can ask a yes or no question and then choose a message to display according to the answer. Suppose you want to ask the user whether to continue:
reply = input('Do you want to continue? (y/n): ', 's');
if reply == 'y'
disp('Continuing...');
else
disp('Stopping.');
end
This script treats the reply as text, then compares it against the expected character. If the user types y, one branch runs. If they type anything else, the other branch runs. The conditional logic itself belongs to other chapters, but the combination of input for reading a decision and disp for showing feedback is central for simple user interaction.
Basic Input Validation Ideas
For beginner scripts that use input, it is easy to assume the user enters something correct. In real use, a user might type unexpected values or press Enter without answering. Even without writing complex error handling code, you can start to add very simple checks around input.
Suppose you want the user to enter a positive number such as a radius. You could first read the value, then test it and inform the user if something is wrong:
radius = input('Enter radius (must be positive): ');
if radius <= 0
disp('The radius must be a positive number.');
else
area = pi * radius.^2;
disp(['Area is ', num2str(area)]);
end
This pattern uses input just once, then tests the result and chooses what message to disp. Even though this does not prevent the user from entering bad data, it at least gives a clear response and avoids silently using an invalid value.
For text input using input(...,'s'), you might want to check whether the user left the answer empty. For example:
username = input('Enter a username: ', 's');
if isempty(username)
disp('You did not enter a username.');
else
disp(['Welcome, ', username]);
end
Again, the goal is not to build a complete validation system, but to show how simple checks around input and clear messages with disp can already make interactive scripts more robust and understandable.
Pausing and Guiding the User
Some scripts do not just ask for data. They also guide the user through stages with messages and short pauses. You can use disp to explain what is happening before each step. For instance:
disp('This script processes your data file.');
disp('First, you will choose the file.');
fileName = input('Enter the file name (including extension): ', 's');
disp('Processing the file, please wait...');
% processing code would go here
disp('Done.');
Here, disp keeps the user informed at each step, so they are not surprised when the script pauses for input or takes some time to work.
If you want the user to read something before continuing, a simple pattern is to ask them to press Enter using input without storing the return value:
disp('Step 1 complete.');
input('Press Enter to continue...', 's');
disp('Step 2 starting.');
In this case, the string typed by the user is not used. The call to input only creates a pause and a clear moment where the user decides when to proceed.
Combining User Input with Automation
The main purpose of user interaction in automation scripts is to select a few key options, then let MATLAB handle the rest without further questions. A typical pattern is to collect one or more settings from input, then run several automated steps based on them.
Imagine a script that can run in either a test mode or a full mode. You can ask the user once at the beginning which mode they want, then use that choice to control the rest of the script:
mode = input('Choose mode (1 = test, 2 = full): ');
if mode == 1
disp('Running in test mode...');
% test mode actions
elseif mode == 2
disp('Running in full mode...');
% full mode actions
else
disp('Unknown mode selected.');
end
In another example, you can ask the user how many times to repeat an operation, or which folder to process, or which option to apply. In all cases, the pattern is the same. Read a value with input, display clear messages with disp, and then let the rest of the script follow those choices automatically without further manual editing.
This approach keeps your scripts flexible while still being easy to use for someone who only interacts through the Command Window.
Key points to remember:
Use input('prompt') when you expect numeric expressions and want MATLAB to evaluate what the user types.
Use input('prompt', 's') when you expect text, such as names or codes, and you do not want MATLAB to evaluate the input.
Use disp(value) to display results or messages simply, without variable names or formatting codes.
Combine input and disp to build small interactive scripts that ask questions once, then run automated steps based on the answers.