3.Characters and Strings
In MATLAB, several characters (Character) can form a string (String). A string is considered a row vector, and each character in the string (including space characters) is stored in each element of this vector in its ASCII form, although its visible representation remains readable characters. The string type plays a very important role in data visualization and application interaction.
3.1 Creating Strings
1. General String Creation
In MATLAB, all strings are enclosed in two single quotes for input assignment. For example, in the MATLAB command window, input:
>> a=’matlab’
a =
matlab
Each character of the string (spaces are also characters) is an element of the corresponding matrix, and the variable a is a 1×6 matrix, which can be checked using the size(a) command:
>> size(a)
ans =
1 6 % 1 row 6 columns
2. Creating Chinese Strings
Chinese can also be used as the content of a string. However, it is important to note that during the input process of Chinese strings, the single quotes on both sides must be in English state. For example:
>> A=’Chinese string input demonstration‘
A =
Chinese string input demonstration
3. String Indexing
In MATLAB, string indexing can be achieved through its coordinates. In a string, MATLAB assigns numbers to the characters in the string from left to right (1,2,3,…). To index a string, simply treat it like indexing a regular matrix. For example, after creating the Chinese string A, you can obtain:
>> A(3:5)
ans =
string
4. Creating String Arrays
Creating a two-dimensional string (array) is also very simple. It can be directly input like a numerical array, or it can be created using functions like str2mat.
[Example 3-6] Direct input example of a multi-line string array.
>> clear
>> S=[‘This string array ‘
‘has multiple rows.’]
S =
This string array
has multiple rows.
>> size(S)
ans =
2 18
It is important to note that when directly inputting a multi-line string array, the number of characters in each line must be the same.
[Example 3-7] Example of creating a multi-line string array using the str2mat function.
>> a=str2mat(‘this‘,’character‘,’string array‘,”,’composed of5 rows‘)
a =
this
character
string array
composed of5 rows
>> size(a)
ans =
5 6
When using the str2mat function to create a string array, there is no need to worry about whether the number of characters in each row is equal; the function will pad the other rows with spaces to match the longest row.
3.2 String Comparison
In MATLAB, there are various functions for comparing strings:
(1) Compare whether two strings or substrings are equal;
(2) Compare whether individual characters in a string are equal;
(3) Classify elements within a string to determine if each element is a character or a space.
Users can use any of the following four functions to determine if two input strings are equal:
(1) strcmp: Determines if two strings are equal.
(2) strncmp: Determines if the first n characters of two strings are equal.
(3) strcmpi and strncmpi: These two functions serve the same purpose as strcmp and strncmp, respectively, but ignore letter case during comparison.
Consider the following two strings:
>>str1 = ‘hello’;
>>str2 = ‘help’;
The strings str1 and str2 are not equal, so using the strcmp function will return a logical 0 (false). For example:
>>C = strcmp(str1,str2)
C =
0
Since the first 3 characters of str1 and str2 are equal, using the strncmp function to compare the first 3 characters will return a logical 1 (true). For example:
>>C = strncmp(str1, str2, 2) % Compare the first two characters
C =
1
Next, we will introduce how to compare in cases of different letter cases.
>> str3 = ‘Hello’;
>> D = strncmp(str1, str3,2) % Case-sensitive comparison
D =
0
>> F = strncmpi(str1, str3,2) % Case-insensitive comparison
F =
1
Users can use relational operators to compare strings, as long as the arrays being compared have the same size, or one is a scalar. For example, the (==) operator can be used to determine which characters are equal in the two strings.
>>A = ‘fate’;
>>B = ‘cake’;
>>A == B
ans =
0 1 0 1
All relational operators can be used to compare characters at corresponding positions in strings.
3.3 String Searching and Replacing
MATLAB provides many functions for users to search and replace strings. More powerfully, MATLAB also supports the use of regular expressions in string searching and replacing. By flexibly using regular expressions, various forms of searching and replacing can be performed on strings. For the application of regular expressions, users can refer to the Regular Expressions section in the help documentation.
[Example 3-8] Using the strrep function for string searching and replacing.
Consider the following label:
>> label = ‘Sample 1, 03/28/15’
label =
Sample 1, 03/28/15
The function strrep is used to implement general searching and replacing functionality. In this example, we use the strrep function to replace the date from “03/28” to “03/30“. The command is as follows:
>> newlabel = strrep(label, ’28’, ’30’)
newlabel =
Sample 1, 03/30/15
[Example 3-9] Using the findstr function for string searching.
The findstr function returns the starting positions of a substring within the entire string. For example, to find the positions of the letter a and oo in a string, you can use the following commands:
>> strtemp=’have a good time!’
strtemp =
have a good time!
>> position1= findstr(‘a’, strtemp)
position1 =
2 6
>> position2 = findstr(‘oo’, strtemp)
position2 =
9
This example shows that the letter a appears at positions 2 and 6, indicating that the findstr function returns the position information of all occurrences of the substring. The letter ‘oo‘ appears only once, so it returns only one position information.
The strtok function returns the characters before the first occurrence of a delimiter. If no delimiter is specified, the default delimiter is whitespace characters, so users can use the strtok function to split a sentence into words.
[Example 3-10] Using the strtok function for string searching.
>> t=’I have walked out on a handful of movies in my life.’; % Test string
>> remain = t;
>> while true % Using while loop structure
[str, remain] = strtok(remain); % Search using default whitespace as delimiter
if isempty(str), break; end % Loop exit control
disp(sprintf(‘%s’, str)) % Display result
end
The following are the results obtained using the strtok function for multiple searches:
I
have
walked
out
on
a
handful
of
movies
in
my
life.
The strmatch function is used to find strings in a character array that start with a specified substring, returning the line numbers of those strings.
[Example 3-11] Using the strmatch function for string searching.
>> maxstrings = strvcat(‘max’, ‘minimax’,’maximum’) % Test string array
maxstrings =
max
minimax
maximum
>> strmatch(‘max’, maxstrings) % Search for strings starting with max in the test string array
ans =
1
3
In this example, the second line minimax also contains the substring max, but this substring does not start with max, so it is not returned in the search results.
3.4 Type Conversion
In MATLAB, it is allowed to convert between different types of data and string types, and this conversion requires the use of different functions. Additionally, the same data, especially integer data, can have many different formats, such as decimal, binary, or hexadecimal. In C language, the printf function can be used to output data in different formats through the corresponding format string. In MATLAB, there are corresponding functions available to perform base conversions. Tables 3-2 and 3-3 list these functions.
Table 3-2 Conversion Functions Between Numbers and Strings
Function |
Description |
Function |
Description |
num2str |
Convert number to string |
str2num |
Convert string to number |
int2str |
Convert integer to string |
sprintf |
Format output data to command window |
mat2str |
Convert matrix to a string usable by eval function |
sscanf |
Read formatted string |
str2double |
Convert string to double precision data |
Table 3-3 Conversion Functions Between Different Numeric Types
Function |
Description |
Function |
Description |
hex2num |
Convert hexadecimal integer string to double precision data |
dec2bin |
Convert decimal integer to binary integer string |
hex2dec |
Convert hexadecimal integer string to decimal data |
base2dec |
Convert a numeric string of specified base type to decimal integer |
dec2hex |
Convert decimal data to hexadecimal integer string |
dec2base |
Convert decimal integer to a numeric string of specified base type |
bin2dec |
Convert binary integer string to decimal integer |
Among the conversion functions listed in Table 3-2, the most commonly used are num2str and str2num. These two functions are often used in MATLAB graphical user interface programming.
[Example 3-12] Examples of using num2str and str2num functions.
>> a=[‘1 2′;’3 4’] % Create a string array
a =
1 2
3 4
>> b=str2num(a) % Convert string to numeric form
b =
1 2
3 4
>> c=str2num(‘1+2i’) % Convert string to numeric form
c =
1.0000 +2.0000i
>> d=str2num(‘1 +2i’) % Convert string to numeric form
d =
1.0000 +0.0000i 0.0000 + 2.0000i>>e=num2str(rand(3,3),6) % Convert number to string form
e =
0.814724 0.913376 0.278498
0.905792 0.632359 0.546882
0.126987 0.0975404 0.957507
>> whos
Name Size Bytes Class Attributes
a 2×3 12 char
b 2×2 32 double
c 1×1 16 double complex
d 1×2 32 double complex
e 3×35 210 char
In this example, different results were obtained when converting to variables c and d, mainly because in variable d, there is a space between the number “1” and the character “+2i” while there is no space between the plus sign “+” and the number “2. To avoid this issue, the str2double function can be used, but this function can only convert scalars, not matrices or arrays.
When using the num2str function to convert numbers to strings, you can specify the number of significant digits represented by the string; for more details, refer to the MATLAB help documentation.
3.5 Summary of String Application Functions
MATLAB is primarily known for matrix calculations, but in addition, this software also provides a series of very powerful functions for string processing. Table 3-4 summarizes commonly used string functions.
Table 3-4 String Functions
Function |
Description |
|
String Creation Functions |
‘str’ |
Create a string with single quotes (in English state) |
blanks |
Create a space string |
|
sprintf |
Write formatted data into a string |
|
strcat |
String concatenation |
|
strvcat |
Vertical string concatenation |
|
String Modification Functions |
deblank |
Remove trailing spaces |
lower |
Convert all characters to lowercase |
|
sort |
Sort all elements in ascending or descending order |
|
strjust |
String alignment |
|
strrep |
String replacement |
|
strtrim |
Remove leading and trailing whitespace characters |
|
upper |
Convert all characters to uppercase |
|
String Reading and Manipulation |
eval |
Execute a string as a MATLAB command |
sscanf |
Format read string |
Continued Table
Function |
Description |
|
String Searching and Replacing Functions |
findstr |
Find substring |
strcmp |
String comparison |
|
strcmpi |
String comparison, ignoring case |
|
strmatch |
Find matching rows |
|
strncmp |
Compare the first N characters of strings |
|
strncmpi |
Compare the first N characters of strings, ignoring case |
|
strtok |
Find the first occurrence of a character |
Edited by: Qingying, Qingguo Qingcheng, Pengbi Shenghui
Reviewed by: Shuyun Campus Studio
If you are interested in the topic,
you can click the lower left corner “Read the original text” to enter the community and leave a message
or directly click below to leave us a message