Strings


>> In this tutorial we will discuss about the strings in MATLAB. Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you type the following in the command prompt as shown. Click on the picture to see.



MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use the whos command to check the variable created above:


Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the string to their numeric codes. The char function converts the integer vector back to characters:

Example:

Create a script file and type the following code into it:



my_string = 'Tutorial' 's Point';

str_ascii = uint8(my_string)        % 8-bit ascii values

str_back_to_char= char(str_ascii)  

str_16bit = uint16(my_string)       % 16-bit ascii values

str_back_to_char = char(str_16bit)

When you run the file, it displays the following result. Click on the picture to see.



Rectangular Character Array:



The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular character arrays. Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional character arrays, either vertically or horizontally as required. You can combine strings vertically in either of the following ways:



>> Using the MATLAB concatenation operator [ ] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed.



>> Using the char function. If the strings are different length, char pads the shorter strings with trailing blanks so that each row has the same number of characters.

Example:

>> Create a script file and type the following code into it:

doc_profile = ['Zara Ali '; ...
               'Sr. Surgeon '; ...
               'R N Tagore Cardiology Research Center']
doc_profile = char('Zara Ali', 'Sr. Surgeon', ...
                   'RN Tagore Cardiology Research Center')

>> When you run the file, it displays the following result:

doc_profile =
Zara Ali                             
Sr. Surgeon                          
R N Tagore Cardiology Research Center
doc_profile =
Zara Ali                            
Sr. Surgeon                         
RN Tagore Cardiology Research Center

>> You can combine strings horizontally in either of the following ways:



1. Using the MATLAB concatenation operator, [ ] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays.



2. Using the string concatenation function, strcat. This method removes trailing spaces in the inputs


Example:



>> Create a script file and type the following code into it:



name =     'Zara Ali ';

position = 'Sr. Surgeon '; 

worksAt =  'R N Tagore Cardiology Research Center';
profile = [name ', ' position ', ' worksAt]
profile = strcat(name, ', ', position, ', ', worksAt)

>> When you run the file, it displays the following result:

profile =
Zara Ali                             , Sr. Surgeon                          , R N Tagore Cardiology Research Center
profile =
Zara Ali,Sr. Surgeon,R N Tagore Cardiology Research Center

Combining Strings into a Cell Array:

From our previous discussion, it is clear that combining strings with different lengths could be a pain as all strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize their length. However, a more efficient way to combine the strings is to convert the resulting array into a cell array. MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of varying length. 

The cellstr function converts a character array into a cell array of strings.

Example

>> Create a script file and type the following code into it:


name =     ' Zara Ali ';

position = ' Sr. Surgeon '; 
worksAt =  ' R N Tagore Cardiology Research Center ';
profile = char(name, position, worksAt) ;
profile = cellstr(profile) ;
disp(profile)

>> When you run the file, it displays the following result:


' Zara Ali '

' Sr. Surgeon '

' R N Tagore Cardiology Research Center '

String Functions in MATLAB

MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating strings. Following table provides brief description of the string functions in MATLAB. Click image to see.



Examples

The following examples illustrate some of the above-mentioned string functions:


FORMATTING STRINGS

>> Create a script file and type the following code into it:

A = pi*1000*ones(1,5);

sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)

>> When you run the file, it displays the following result:


ans =

 3141.592654 
 3141.59 
 +3141.59 
      3141.59 
 000003141.59

JOINING STRINGS

>> Create a script file and type the following code into it:

%cell array of strings

str_array = {'red','blue','green', 'yellow', 'orange'};

% Join strings in cell array into single string

str1 = strjoin("-", str_array)
str2 = strjoin(",", str_array)

>> When you run the file, it displays the following result:


str1 =

red blue green yellow orange
str2 =
red , blue , green , yellow , orange

FINDING AND REPLACING STRINGS

>> Create a script file and type the following code into it:

students = {'Zara Ali', 'Neha Bhatnagar', ...

            'Monica Malik', 'Madhu Gautam', ...
            'Madhu Sharma', 'Bhawna Sharma',...
            'Nuha Ali', 'Reva Dutta', ...
            'Sunaina Ali', 'Sofia Kabir'};

% The strrep function searches and replaces sub-string.

new_student = strrep(students(8), 'Reva', 'Poulomi')
% Display first names
first_names = strtok(students)

>> When you run the file, it displays the following result:


new_student = 

    'Poulomi Dutta'
first_names = 
  Columns 1 through 6
    'Zara'    'Neha'    'Monica'    'Madhu'    'Madhu'    'Bhawna'
  Columns 7 through 10
    'Nuha'    'Reva'    'Sunaina'    'Sofia'

COMPARING STRINGS

>> Create a script file and type the following code into it:

str1 = 'This is test'

str2 = 'This is text'
if (strcmp(str1, str2))
 sprintf('%s and %s are equal', str1, str2)
else
 sprintf('%s and %s are not equal', str1, str2)
end

>> When you run the file, it displays the following result:


str1 =

This is test
str2 =
This is text
ans =

This is test and This is text are not equal