Ch6 Matrices of numbers & arrays of strings

Obtain your own copy of the files for Chapter 6

From the UNIX prompt on rohan:

mkdir ch6
cd ch6
cp ~stewart/cs205/ch6*/* .
ls
should show
errortrap1.m errortrap2.m loanfors.m loaninnervect.m

go to 6.4 Strings (13 October 2008)
go to 6.6 eval and text macros (15 October 2008)

6.1 Matrices - lecture topic (08 October 2008)
6.1.1 - 6.1.13 A concrete example
Lots of examples using the colon operator to create matrices and create matrices from other matrices.
6.1.15 Vectorizing nested fors: loan repayment tables
  1. loanfors.m conventional

    >> ls
    errortrap1.m  loanfors.m
    errortrap2.m  loaninnervect.m
    >> tic
    >> loanfors
      10     10.75      9.65      9.09
      11     11.37     10.32      9.80
      12     12.00     11.01     10.53
      13     12.65     11.72     11.28
      14     13.32     12.44     12.04
      15     14.00     13.17     12.81
      16     14.69     13.91     13.59
      17     15.39     14.67     14.38
      18     16.10     15.43     15.17
      19     16.83     16.21     15.98
      20     17.56     16.99     16.78
    >> toc
    Elapsed time is 5.374843 seconds.
    
  2. loaninnervect.m vectorized for

    >> tic
    >> loaninnervect
       10.0000   10.7461    9.6502    9.0870
       11.0000   11.3660   10.3219    9.8011
       12.0000   12.0017   11.0109   10.5322
       13.0000   12.6524   11.7158   11.2784
       14.0000   13.3174   12.4352   12.0376
       15.0000   13.9959   13.1679   12.8083
       16.0000   14.6870   13.9126   13.5889
       17.0000   15.3900   14.6680   14.3780
       18.0000   16.1042   15.4331   15.1743
       19.0000   16.8288   16.2068   15.9768
       20.0000   17.5630   16.9882   16.7845
    
    >> toc
    Elapsed time is 22.090842 seconds.
    
    Note: Stewart deleted some blank lines in the output of loaninnervect.m above.

    Do you notice something odd in the run-times above?

    Analyzing Your Program's Performance from online MATLAB documentation Open this is a new window. Then Select Index; Select "the letter p"; and scroll down to Performance to find Analyzing your Program's Performance

6.2 Matrix operations - 6.3 other matrix functions
Arrays operations can be performed element by element on matrices using the .* or .+ operations.
Matrix operations, fundamental to MATLAB, are defined in the mathematical sense where if C = A B, and number of columns in A is the same as the number of rows in B

ci,j = SUM ai,k bk,j.

Lecture will highlight many of these examples.


6.4 Other matrix functions
det determinant
eig eigenvalue decomposition
expm matrix exponential, i.e. eA where A is a matrix.
matrix exponential is useful in solving linear ordinary differential equations
inv inverse
lu LU factorization into lower and upper triangular matrices
qr QR orthogonal factorization
svd singular value decompostion


6.4 Strings - 6.5 Two-dimensionsl strings (13 October 2008)
Next week (Oct 13) lecture will highlight these.

6.4.1 assignment
s1 = 'Hi There';
s2 = ' 10 o''clock'; need to use double apostrophe (note this is NOT " the double-quote character)
6.4.2 Input
strings may be entered in response to the input statement in 2 ways
  1. prompt the user to use apostrophe, e.g. s = input ('enter a string - using the apostrophe to enclose where you type it');
  2. or you can indicate in the input statement that a string is expected , e.g. s = input (' enter a string ','s');
6.4.3 Strings are arrays
a MATLAB string is an array with each element representing one character in the string. If
s = 'Napoleon';
then whos
>> s = 'napoleon';
>> whos
  Name      Size            Bytes  Class    Attributes
  s         1x8                16  char               
showing s is a 1x8 char vector. The statement s(8:1:-1) will display the string backwards

>> s(8:-1:1)
ans =
noelopan
>>

If a string must contain an apostrophe, the apostrophe must be repeated when entering the string. However, only one apostrophe is actually stored in the string. For example, in
name = 'M''kombe'
name(3) is 'k'

Why is this done? The computer system (MATLAB) needs to distinguish the string delimiter (') from the character (').

>> name = 'M''kombe'
name =
M'kombe
>> name(3)
ans =
k
>> whos
  Name      Size            Bytes  Class    Attributes
  ans       1x1                 2  char               
  name      1x7                14  char               
  s         1x8                16  char  
We can exploit the vector nature of strings in many ways. For example, to remove all the blanks from the string s. This use a logical vector (nonblanks) too.
>> s = 'Twas brillig and the sithy toves';
>> nonblanks = s ~= ' ';
>> s (nonblanks)
ans =
Twasbrilligandthesithytoves
>> whos
  Name           Size            Bytes  Class      Attributes
  ans            1x26               52  char                 
  name           1x7                14  char                 
  nonblanks      1x32               32  logical              
  s              1x32               64  char                 

6.4.4 Concatenation of strings
Treating strings as vectors, we use square brackets to catenate.
>> king = 'Henry';
>> king = [king, ' VIII']
king =
Henry VIII

>> whos
  Name           Size            Bytes  Class      Attributes

  ans            1x26               52  char                 
  king           1x10               20  char                 
  name           1x7                14  char                 
  nonblanks      1x31               31  logical              
  s              1x31               62  char                 
6.4.5 ASCII codes, double and char
A MATLAB character is represented internally by a 16-bit numerical value. The character codes start at 1; the first 127 such codes are the ASCII codes. the letters 'A' to 'Z' are the consecutive integers from 65 to 90, while the codes for 'a' to 'z' are 97 to 122. This is Appendix D of our text, or you can check online, http://www.asciitable.com/ for an ASCII table.

>> double ('napoleon')
ans =
   110    97   112   111   108   101   111   110
>> 
or use the char function to convert integers to ASCII codes
>> char(65:70)
ans =
ABCDEF
>> 

Use char and double to generate rows of identical characters

>> x = char(ones(4,20)*double('#'))
x =
####################
####################
####################
####################
>> 
ones(4,20) generates 4 rows and 20 columns of 1's (or true). Multiplying by double('#') replaces the 1's with ASCII code for '#' and char converts the ASCII codes back to text.

If a character variable is involved in an arithmetic expression, MATLAB uses the ASCII code of the character in the calculation.

>> s = 'a';
>> s+1
ans = 
  98
>>
Array operations can be performed on string. If s is a string of letters, the expression char(s+1) returns each letter in the string advanced by one place in the alphabet.

The relationship between characters and their ASCII codes means you can do neat things

>> alpha = double ('a'):double('z')
alpha =
  Columns 1 through 11
    97    98    99   100   101   102   103   104   105   106   107
  Columns 12 through 22
   108   109   110   111   112   113   114   115   116   117   118
  Columns 23 through 26
   119   120   121   122
>> 

6.5.4 fprintf of strings
>> fprintf (' %8sVIII\n', 'Henry')
    HenryVIII
>> fprintf ('%-8sVIII\n', 'Henry')
Henry   VIII
>> fprintf ('%.3sVIII\n', 'Henry')
HenVIII
>> 

6.4.7 Comparing strings
>> s1 = 'ann';
>> s2 = 'ban';
>> s1 < s2
ans =
     1     0     0
>> 
the result of the logical comparison, element by element, of the two character vectors, s1 and s2. NOTE: strings must have the same length.

The function strcmp(s1,s2) compares the two strings s1 and s2, returning 1 if they are identical and 0 otherwise. In this case, the strings DO NOT have to be the same length.

6.4.8 other string functions
blanks, deblank, int2str, num2str, ischar, lower, upper, sprintf

6.5 Two-dimensional strings
>> nameAndAddress = ['Adam B Carr  '; '21 Barkly Ave'; 'Discovery  ']
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.
What generated this Error message? We needed to ensure the same number of characters (13) in each column of the array nameAndAddress.

>> nameAndAddress = char('Adam B Carr', '21 Barkly Ave', 'Discovery')
nameAndAddress =
Adam B Carr  
21 Barkly Ave
Discovery    
>> whos
  Name                Size            Bytes  Class      Attributes
  nameAndAddress      3x13               78  char                 
>> 
It is easier to let MATLAB do the padding of the data for you. Also, remember that if you use single-subscript notation the array is referenced by column, so
>> nameAndAddress(1:3)
ans =
A2D
>> 
the first letter of each row.


6.6 *eval and text macros - Wednesday 15Oct2008
If a MATLAB expression is encoded as a string in a variable t, then the function eval(t) causes the expression in t to be evaluated. Strictly speaking, the string is interpreted. Thius is called a text macro facility. For example, if the assignment

s = 'x = -b / (2*a);'

is made, eval(s) makes MATLAB interpet the text in s as the statement

x = -b / (2*a);

which is carried out with the current values of a and b.

Another use of eval could be as a "user-friendly" way of inputting a function from the Command Window. Consideer the following script:

f = input ('Enter function (of x) to be plotted: ', 's');
x = 0 : 0.01 : 10;
plot(x,eval(f)),grid
This was created and called p165eval.m and is available to you.

We will see in Chapter 10: Function handles that we will prefer to use feval rather than eval whenever possible, since feval is faster and the code using it can be compiled with the MATLAB compiler.


6.6.1 Error trapping with eval and lasterr
The use of eval to evaluate an expression which is input by a user can misfire if the user enters an invalid expression; the script grinds to a halt. However, eval together with the function lasterr enables the programmer to trap and correct errors like this.

the function eval can take a second (string) argument, representing an expression to be executed if an error is encountered in the first argument. We demonstrate this with errortrap1.m below. errortrap1.m errortrap2.m