Matlab

How To Take String Input in MATLAB

Taking string input is a common task when working with MATLAB, especially when interacting with users or reading data from external sources. In this article, we will explore different methods to efficiently take string input in MATLAB, along with examples for each approach.

How To Take String Input in MATLAB

To get string input in MATLAB there are different ways:

Method 1: Using the input() Function

The simplest way to take string input in MATLAB is by using the input() function, here’s an example code in this regard:

% Prompt the user for string input
userInput = input('Enter a string: ', 's');

% Display the entered string
disp(['You entered: ', userInput]);

 
In this code, the input() function is used to prompt the user to enter a string. The second argument s is passed to indicate that the input should be treated as a string. The entered string is then stored in the variable userInput and can be further processed or displayed as desired.

Method 2: Using the strtrim() Function

Here is an example of how to use the strtrim() function to eliminate leading and trailing whitespace from a string input:

% Prompt the user for string input
userInput = input('Enter a string: ', 's');

% Trim leading and trailing whitespace
trimmedInput = strtrim(userInput);

% Display the trimmed string
disp(['Trimmed string: ', trimmedInput]);

 
In this code, the strtrim() function is applied to the input string userInput to remove any leading or trailing whitespace. The trimmed string is stored in the variable trimmedInput and can be used for further processing or display.

Method 3: Using File I/O Functions

If you need to read a string input from a file, MATLAB provides several file input/output functions that can be used. One such function is fgetl(), which reads a line of text from a file. Here’s an example:

% Open the file for reading
fileID = fopen('file.txt', 'r');

% Read the string input from the file
userInput = fgetl(fileID);

% Close the file
fclose(fileID);

% Display the string input
disp(['String input from file: ', userInput]);

 
In this code, the file file.txt is opened for reading using the fopen() function. The fgetl() function is then used to read a line of text from the file, which is stored in the variable userInput and then the file is closed using fclose().

Conclusion

Taking string input in MATLAB can be achieved using various methods such as the input() function for user input, strtrim() for trimming whitespace, or file I/O functions for reading from files. By employing these approaches, you can effectively handle string inputs and enhance the functionality of your MATLAB programs.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.