How to Read Each Character of a String in Matlab

MATLAB - Strings


Creating a character string is quite simple in MATLAB. In fact, we accept used it many times. For example, you type the following in the command prompt −

my_string = 'Tutorials Betoken'        

MATLAB volition execute the above statement and return the following result −

my_string = Tutorials Point        

MATLAB considers all variables as arrays, and strings are considered as grapheme arrays. Let us use the whos command to check the variable created to a higher place −

whos        

MATLAB will execute the in a higher place statement and render the following upshot −

Name           Size            Bytes  Form    Attributes my_string      1x16               32  char        

Interestingly, you can use numeric conversion functions similar uint8 or uint16 to catechumen the characters in the string to their numeric codes. The char part converts the integer vector dorsum to characters −

Example

Create a script file and type the post-obit code into it −

my_string = 'Tutorial''s Betoken'; str_ascii = uint8(my_string)        % viii-bit ascii values str_back_to_char= char(str_ascii)   str_16bit = uint16(my_string)       % 16-chip ascii values str_back_to_char = char(str_16bit)        

When you run the file, it displays the following issue −

str_ascii =     84  117  116  111  114  105   97  108   39  115   32   80  111  105  110  116  str_back_to_char = Tutorial's Betoken str_16bit =     84  117  116  111  114  105   97  108   39  115   32   eighty  111  105  110  116  str_back_to_char = Tutorial'southward Indicate        

Rectangular Graphic symbol Array

The strings we have discussed so far are one-dimensional grapheme arrays; however, we demand to store more than than that. We need to store more dimensional textual information in our program. This is achieved by creating rectangular character arrays.

Simplest fashion of creating a rectangular character array is by concatenating two or more i-dimensional graphic symbol arrays, either vertically or horizontally equally required.

Y'all tin 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 infinite characters as needed.

  • Using the char part. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters.

Example

Create a script file and blazon the following code into it −

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

When you lot run the file, it displays the following effect −

doc_profile = Zara Ali                              Sr. Surgeon                           R Due north Tagore Cardiology Research Center doc_profile = Zara Ali                             Sr. Surgeon                          RN Tagore Cardiology Inquiry Center        

Yous can combine strings horizontally in either of the following means −

  • 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.

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

Example

Create a script file and type the following lawmaking into information technology −

name =     'Zara Ali                             '; position = 'Sr. Surgeon                          ';  worksAt =  'R N Tagore Cardiology Inquiry Center'; profile = [name ', ' position ', ' worksAt] contour = strcat(name, ', ', position, ', ', worksAt)        

When y'all run the file, it displays the following upshot −

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

Combining Strings into a Cell Array

From our previous discussion, information technology is articulate that combining strings with different lengths could be a pain equally all strings in the array has to be of the same length. Nosotros have used blank spaces at the stop 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 tin can hold different sizes and types of information in an assortment. Cell arrays provide a more flexible manner 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 North Tagore Cardiology Enquiry Center'; contour = char(name, position, worksAt); profile = cellstr(profile); disp(contour)        

When y'all run the file, information technology displays the post-obit result −

{                                                                                   [1,i] = Zara Ali                                                                  [2,1] = Sr. Surgeon                                                               [3,1] = R Due north Tagore Cardiology Research Middle                                  }        

String Functions in MATLAB

MATLAB provides numerous cord functions creating, combining, parsing, comparing and manipulating strings.

Following table provides cursory description of the string functions in MATLAB −

Part Purpose
Functions for storing text in grapheme arrays, combine character arrays, etc.
blanks Create cord of blank characters
cellstr Create cell assortment of strings from grapheme array
char Convert to character assortment (cord)
iscellstr Decide whether input is prison cell array of strings
ischar Determine whether particular is character assortment
sprintf Format data into cord
strcat Concatenate strings horizontally
strjoin Join strings in cell assortment into single cord
Functions for identifying parts of strings, find and replace substrings
ischar Determine whether item is character array
isletter Assortment elements that are alphabetic messages
isspace Array elements that are space characters
isstrprop Determine whether string is of specified category
sscanf Read formatted data from string
strfind Find i string within another
strrep Detect and replace substring
strsplit Split string at specified delimiter
strtok Selected parts of string
validatestring Check validity of text string
symvar Determine symbolic variables in expression
regexp Lucifer regular expression (case sensitive)
regexpi Friction match regular expression (case insensitive)
regexprep Supplant string using regular expression
regexptranslate Interpret cord into regular expression
Functions for string comparison
strcmp Compare strings (case sensitive)
strcmpi Compare strings (case insensitive)
strncmp Compare offset due north characters of strings (case sensitive)
strncmpi Compare offset north characters of strings (instance insensitive)
Functions for irresolute string to upper- or lowercase, creating or removing white space
deblank Strip trailing blanks from end of string
strtrim Remove leading and trailing white space from string
lower Catechumen string to lowercase
upper Convert string to uppercase
strjust Justify character array

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 \north', 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 blazon the following code into it −

%cell array of strings str_array = {'red','blue','green', 'yellow', 'orange'};  % Join strings in cell array into unmarried string str1 = strjoin(str_array, "-") str2 = strjoin(str_array, ",")        

When you run the file, information technology displays the following outcome −

str1 = red-blueish-green-yellow-orange str2 = ruby,blue,green,yellow,orange        

Finding and Replacing Strings

Create a script file and type the following lawmaking 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 commencement names first_names = strtok(students)        

When you run the file, it displays the following issue −

new_student =  {    [1,1] = Poulomi Dutta } first_names =  {    [1,1] = Zara    [1,2] = Neha    [1,iii] = Monica    [1,four] = Madhu    [1,5] = Madhu    [1,vi] = Bhawna    [i,vii] = Nuha    [1,8] = Reva    [i,9] = Sunaina    [one,x] = Sofia }        

Comparing Strings

Create a script file and blazon the following code into it −

str1 = 'This is test' str2 = 'This is text' if (strcmp(str1, str2))    sprintf('%s and %due south are equal', str1, str2) else    sprintf('%s and %southward are not equal', str1, str2) finish        

When yous run the file, it displays the following result −

str1 = This is examination str2 = This is text ans = This is exam and This is text are not equal        

Useful Video Courses


Data Preprocessing for Machine Learning using MATLAB

Video

Complete MATLAB Tutorial: Go from Beginner to Expert

Video

Image Processing Toolbox in MATLAB

Video

Matlab - The Complete Course

Video

Digital Image Processing using MATLAB

Video

Backpropagation Learning Method in Matlab

Video

millertherited51.blogspot.com

Source: https://www.tutorialspoint.com/matlab/matlab_strings.htm

0 Response to "How to Read Each Character of a String in Matlab"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel