Showing posts with label matlab. Show all posts
Showing posts with label matlab. Show all posts

Tuesday, July 16, 2019

[ MATLAB Tutorial - Lession 13] String

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 −
 Live Demo
my_string = 'Tutorials Point'
MATLAB will execute the above statement and return the following result −
my_string = Tutorials Point
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 −
whos
MATLAB will execute the above statement and return the following result −
Name           Size            Bytes  Class    Attributes
my_string      1x16               32  char
Interestingly, you can use numeric conversion functions like uint8 or uint16to convert the characters in the string to their numeric codes. The charfunction converts the integer vector back to characters −

Example

Create a script file and type the following code into it −
 Live Demo
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 −
str_ascii =

   84  117  116  111  114  105   97  108   39  115   32   80  111  105  110  116

str_back_to_char = Tutorial's Point
str_16bit =

   84  117  116  111  114  105   97  108   39  115   32   80  111  105  110  116

str_back_to_char = Tutorial's Point

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 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 type the following code into it −
 Live Demo
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 −
  • 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 code into it −
 Live Demo
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 −
 Live Demo
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 −
{                                                                               
   [1,1] = Zara Ali                                                              
   [2,1] = Sr. Surgeon                                                           
   [3,1] = 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 −
FunctionPurpose
Functions for storing text in character arrays, combine character arrays, etc.
blanksCreate string of blank characters
cellstrCreate cell array of strings from character array
charConvert to character array (string)
iscellstrDetermine whether input is cell array of strings
ischarDetermine whether item is character array
sprintfFormat data into string
strcatConcatenate strings horizontally
strjoinJoin strings in cell array into single string
Functions for identifying parts of strings, find and replace substrings
ischarDetermine whether item is character array
isletterArray elements that are alphabetic letters
isspaceArray elements that are space characters
isstrpropDetermine whether string is of specified category
sscanfRead formatted data from string
strfindFind one string within another
strrepFind and replace substring
strsplitSplit string at specified delimiter
strtokSelected parts of string
validatestringCheck validity of text string
symvarDetermine symbolic variables in expression
regexpMatch regular expression (case sensitive)
regexpiMatch regular expression (case insensitive)
regexprepReplace string using regular expression
regexptranslateTranslate string into regular expression
Functions for string comparison
strcmpCompare strings (case sensitive)
strcmpiCompare strings (case insensitive)
strncmpCompare first n characters of strings (case sensitive)
strncmpiCompare first n characters of strings (case insensitive)
Functions for changing string to upper- or lowercase, creating or removing white space
deblankStrip trailing blanks from end of string
strtrimRemove leading and trailing white space from string
lowerConvert string to lowercase
upperConvert string to uppercase
strjustJustify 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 −
 Live Demo
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 −
 Live Demo
%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 −
 Live Demo
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 = 
{
   [1,1] = Poulomi Dutta
}
first_names = 
{
   [1,1] = Zara
   [1,2] = Neha
   [1,3] = Monica
   [1,4] = Madhu
   [1,5] = Madhu
   [1,6] = Bhawna
   [1,7] = Nuha
   [1,8] = Reva
   [1,9] = Sunaina
   [1,10] = Sofia
}

COMPARING STRINGS

Create a script file and type the following code into it −
 Live Demo
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

[ MATLAB Tutorial - Lession 12] Number

MATLAB supports various numeric classes that include signed and unsigned integers and single-precision and double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision floating point numbers.
You can choose to store any number or array of numbers as integers or as single-precision numbers.
All numeric types support basic array operations and mathematical operations.

Conversion to Various Numeric Data Types

MATLAB provides the following functions to convert to various numeric data types −
FunctionPurpose
doubleConverts to double precision number
singleConverts to single precision number
int8Converts to 8-bit signed integer
int16Converts to 16-bit signed integer
int32Converts to 32-bit signed integer
int64Converts to 64-bit signed integer
uint8Converts to 8-bit unsigned integer
uint16Converts to 16-bit unsigned integer
uint32Converts to 32-bit unsigned integer
uint64Converts to 64-bit unsigned integer

Example

Create a script file and type the following code −
 Live Demo
x = single([5.32 3.47 6.28]) .* 7.5
x = double([5.32 3.47 6.28]) .* 7.5
x = int8([5.32 3.47 6.28]) .* 7.5
x = int16([5.32 3.47 6.28]) .* 7.5
x = int32([5.32 3.47 6.28]) .* 7.5
x = int64([5.32 3.47 6.28]) .* 7.5
When you run the file, it shows the following result −
x =

   39.900   26.025   47.100

x =

   39.900   26.025   47.100

x =

   38  23  45

x =

   38  23  45

x =

   38  23  45

x =

   38  23  45

Example

Let us extend the previous example a little more. Create a script file and type the following code −
 Live Demo
x = int32([5.32 3.47 6.28]) .* 7.5
x = int64([5.32 3.47 6.28]) .* 7.5
x = num2cell(x)
When you run the file, it shows the following result −
x =

   38  23  45

x =

   38  23  45

x = 
{
   [1,1] = 38
   [1,2] = 23
   [1,3] = 45
}

Smallest and Largest Integers

The functions intmax() and intmin() return the maximum and minimum values that can be represented with all types of integer numbers.
Both the functions take the integer data type as the argument, for example, intmax(int8) or intmin(int64) and return the maximum and minimum values that you can represent with the integer data type.

Example

The following example illustrates how to obtain the smallest and largest values of integers. Create a script file and write the following code in it −
 Live Demo
% displaying the smallest and largest signed integer data
str = 'The range for int8 is:\n\t%d to %d ';
sprintf(str, intmin('int8'), intmax('int8'))

str = 'The range for int16 is:\n\t%d to %d ';
sprintf(str, intmin('int16'), intmax('int16'))

str = 'The range for int32 is:\n\t%d to %d ';
sprintf(str, intmin('int32'), intmax('int32'))

str = 'The range for int64 is:\n\t%d to %d ';
sprintf(str, intmin('int64'), intmax('int64'))
 
% displaying the smallest and largest unsigned integer data
str = 'The range for uint8 is:\n\t%d to %d ';
sprintf(str, intmin('uint8'), intmax('uint8'))

str = 'The range for uint16 is:\n\t%d to %d ';
sprintf(str, intmin('uint16'), intmax('uint16'))

str = 'The range for uint32 is:\n\t%d to %d ';
sprintf(str, intmin('uint32'), intmax('uint32'))

str = 'The range for uint64 is:\n\t%d to %d ';
sprintf(str, intmin('uint64'), intmax('uint64'))
When you run the file, it shows the following result −
ans = The range for int8 is:
 -128 to 127 
ans = The range for int16 is:
 -32768 to 32767 
ans = The range for int32 is:
 -2147483648 to 2147483647 
ans = The range for int64 is:
 0 to 0 
ans = The range for uint8 is:
 0 to 255 
ans = The range for uint16 is:
 0 to 65535 
ans = The range for uint32 is:
 0 to -1 
ans = The range for uint64 is:
 0 to 18446744073709551616 

Smallest and Largest Floating Point Numbers

The functions realmax() and realmin() return the maximum and minimum values that can be represented with floating point numbers.
Both the functions when called with the argument 'single', return the maximum and minimum values that you can represent with the single-precision data type and when called with the argument 'double', return the maximum and minimum values that you can represent with the double-precision data type.

Example

The following example illustrates how to obtain the smallest and largest floating point numbers. Create a script file and write the following code in it −
 Live Demo
% displaying the smallest and largest single-precision 
% floating point number
str = 'The range for single is:\n\t%g to %g and\n\t %g to  %g';
sprintf(str, -realmax('single'), -realmin('single'), ...
   realmin('single'), realmax('single'))

% displaying the smallest and largest double-precision 
% floating point number
str = 'The range for double is:\n\t%g to %g and\n\t %g to  %g';
sprintf(str, -realmax('double'), -realmin('double'), ...
   realmin('double'), realmax('double'))
When you run the file, it displays the following result −
ans = The range for single is:                                                  
        -3.40282e+38 to -1.17549e-38 and                                        
         1.17549e-38 to  3.40282e+38                                            
ans = The range for double is:                                                  
        -1.79769e+308 to -2.22507e-308 and                                      
         2.22507e-308 to  1.79769e+308
Back to Top