Arrays (cont.
Tan Do
Vietnamese-German University
Lecture 3
Tan Do (VGU) Programming for engineers Lecture 3 1 / 27
Content
In this lecture
Polynomials: representing a polynomial as an array, operations on
polynomials, plotting, polyval command.
Character array.
Structure array.
Cell array.
sprintf command and script le.
Tan Do (VGU) Programming for engineers Lecture 3 2 / 27
Polynomials via arrays
Representing polynomials as arrays
The polynomial
f (x) = an xn + an−1 xn−1 + . . . + a1 x + a0
is represented in MATLAB by the row vector
h i
an an−1 . . . a1 a0
Note the descending order of the vector starting from the coecients of
the highest power of x.
For examples,
2x3 − 5x2 + 7x + 10 is represented as [2, −4, 7, 10].
9x2 + 1 is represented as [9, 0, 1].
Tan Do (VGU) Programming for engineers Lecture 3 3 / 27
Polynomials via arrays
Polynomial operations
Addition: Suppose we want to add f (x) = 2x3 − 5x2 + 7x + 10 to
g(x) = 9x2 + 1.
The representation of f and g are f = [2, −4, 7, 10] and g = [9, 0, 1].
Since we can only add vectors of the same dimension, we have to
rewrite g as g = [0, 9, 0, 1].
In MATLAB, type
» f+g
Subtraction: Similar as addition.
Tan Do (VGU) Programming for engineers Lecture 3 4 / 27
Polynomials via arrays
Multiplication: The multiplication of a polynomial by a constant is
simply a vector scaling. For example, to compute 5 (9x2 + 1), type
» 5 * [9, 0, 1]
To multiply two polynomials f and g together, the syntax is
» conv(f,g) % conv stands for “convolve”
Division: To divide f by g , type
» deconv(f,g) % deconv stands for “deconvolve”
This give the quotient of f dividing by g .
To compute the remainder in the division also, type
» [q,r] = deconv(f,g)
where q stores the quotient and r remainder.
Tan Do (VGU) Programming for engineers Lecture 3 5 / 27
Polynomials via arrays
Polynomial roots
To compute the roots of a polynomial f , the syntax is roots(f).
For example,
» roots([9, 0, 1])
ans =
0.0000 + 0.3333i
0.0000 - 0.3333i
To obtain a polynomial whose roots are stored in the vector r, use poly(r).
For example,
» poly([0.0000 + 0.3333i, 0.0000 - 0.3333i])
ans =
1.0000 0 0.1111
Note that this is the same as the polynomial g = [9, 0, 1] since
» 9 * [1.0000, 0, 0.1111]
ans =
9.0000 0 0.9998
Tan Do (VGU) Programming for engineers Lecture 3 6 / 27
Polynomials via arrays
Polynomial plotting
To evaluate f (x) = 2x3 − 5x2 + 7x + 10 at the values x = 0, 2, 4, . . . , 10, type
» polyval([2,-5,7,10],[0:2:10])
MATLAB then returns a row vector containing 6 values f (0), f (2), . . . , f (10) in that
order.
The function polyval is very useful for plotting polynomial.
For example, to plot the above function f within −5 ≤ x ≤ 5, type
» x = -5:0.01:5; % We choose stepsize 0.01 (small enough) to obtain a smooth plot
» f = polyval([2,-5,7,10],x);
» plot(x,f), xlabel(’x’), ylabel(’y’), grid
% Plot f versus x, label x and y axes and put grid on
Tan Do (VGU) Programming for engineers Lecture 3 7 / 27
char arrays
Character encoding
Characters include letters of the alphabet, digits, punctuation marks,
white space and control characters.
White space characters include the space, tab, etc.
Control characters include are characters that cannot be printed, but
accomplish a task (e.g., a backspace or enter)
A character in MATLAB is represented using single quotes (e.g., 'a' or
'3').
The single quotes are essential to denote a character. Without them,
a letter is interpreted as variable name by MATLAB.
Tan Do (VGU) Programming for engineers Lecture 3 8 / 27
char arrays
Characters are stored in MATLAB using the so-called character
encoding.
In the character encoding, all characters are put in a sequence with
equivalent integer values.
Specically, MATLAB uses ASCII encoding (American Standard Code
for Information Interchange).
Standard ASCII has 128 characters with equivalent integers from 0 to
127.
The rst 32 characters are non-printable characters. Letters of the
alphabet are put in dictionary order.
Tan Do (VGU) Programming for engineers Lecture 3 9 / 27
char arrays
Converting characters to equivalent integers
To convert a character, for example 'a', to its equivalent integer, type
» double(’a’)
ans =
97
which shows that 'a' is the 98th character in the character encoding.
The number type is not important, so it is also possible to type
» int32(’a’)
ans =
97
The function char reverses the process.
» char(97)
ans =
a
Tan Do (VGU) Programming for engineers Lecture 3 10 / 27
char arrays
Maths can be done on characters.
» equinum = double(’a’);
» char(equinum + 1)
ans =
b
» ’a’ + 2
ans =
99
Note the dierence when MATLAB displays a number versus a character.
» var = 3
var =
3
» var = ’3’
var =
3
Tan Do (VGU) Programming for engineers Lecture 3 11 / 27
char arrays
char arrays
Denition A sequence of characters is called a char array or a string.
For example, 'America', 'New Zealand' are strings.
We can concatenate strings together.
s1 = ’New’; s2 = ’Zealand’;
s3 = [s1, ’ ’, s2]
s3 =
New Zealand
An empty string can be created by putting two single quotes together (with no
spacing in between).
s = ”;
c = class(s)
c =
char
Tan Do (VGU) Programming for engineers Lecture 3 12 / 27
char arrays
To create a string which contains a single quote, for example 'don’t', type
» x = ’don”t’
x =
don’t
To nd the equivalent integers of the characters in a string, type
» double(’America’)
ans =
65 109 101 114 105 99 97
MATLAB handles strings similarly to numeric arrays. So to get the substring
'meri' of the string 'America', we can type
» s = ’America’;
» substr = s(2:5)
substr =
meri
Tan Do (VGU) Programming for engineers Lecture 3 13 / 27
char arrays
sprintf function
A very useful function in MATLAB is sprintf.
The sprintf function writes new data to a preformatted string.
Example
» Intro = sprintf(’Hello! My name is %s.’, ’Tan’)
Intro =
Hello! My name is Tan.
» s = sprintf(’This %s class has roughly %d students.’, ’EEIT’, 30)
s =
This EEIT class has roughly 30 students.
» p = sprintf(’An approximation of %s is %f.’, ’pi’, 3.14)
p =
An approximation of pi is 3.14.
Tan Do (VGU) Programming for engineers Lecture 3 14 / 27
struct arrays
Structure terminology
Suppose we want to create a database of students in a course.
We want to include each student's name, Social Security number, email
address and test scores as follows.
Student database
Tan Do (VGU) Programming for engineers Lecture 3 15 / 27
struct arrays
Student database
We call each type of data (student's name, Social Security number, etc.) a eld
and its name the eld name.
In this example, our database has 4 elds. The rst 3 elds contains strings and
the last eld 'test scores' contains a numeric vector.
A structure consists of all this information for a single student. A structure array
is an array of such structures for dierent students.
Tan Do (VGU) Programming for engineers Lecture 3 16 / 27
struct arrays
Creating structures
There are two ways to create a structure:
1 Using struct function.
2 Using the assignment operator.
We rst use struct function to create the structure for student John Smith.
» student = struct(’name’, ’John Smith’, ...
’SSN’, ’392-77-1786’, ...
’email’, ’smithj@myschool.edu’, ...
’tests’, [67, 75, 84]);
» student
student =
name: ’John Smith’
SSN: ’392-77-1786’
email: ’smithj@myschool.edu’
tests: [67 75 84]
Tan Do (VGU) Programming for engineers Lecture 3 17 / 27
struct arrays
To add student Mary Jones to the database, type
» student(2) = struct(’name’, ’Mary Jones’, ...
’SSN’, ’431-56-9832’, ...
’email’, ’jonesm@myschool.edu’, ...
’tests’, [84, 78, 93]);
» student
student =
1x2 struct array with fields:
name
SSN
email
tests
» student(2)
ans =
name: ’Mary Jones’
SSN: ’431-56-9832’
email: ’jonesm@myschool.edu’
tests: [84, 78, 93]
Tan Do (VGU) Programming for engineers Lecture 3 18 / 27
struct arrays
Next we will create a structure using the assignment operator.
» student.name = ’John Smith’;
» student.SSN = ’392-77-1786’;
» student.email = ’smithj@myschool.edu’;
» student.tests = [67, 75, 84];
»
» student(2).name = ’Mary Jones’;
» student(2).SSN = ’431-56-9832’;
» student(2).email = ’jonesm@myschool.edu’;
» student(2).tests = [84, 78, 93];
The above produces the same structure array as that of struct function.
Tan Do (VGU) Programming for engineers Lecture 3 19 / 27
struct arrays
Script le and MATLAB editor
Note that the interactive mode in the Command window requires MATLAB to
execute each command once at a time.
If you nd this inconvenient, you can type and save your structure in a separate
le, called script le, which is available through the MATLAB editor.
Running the script le is then the same as asking MATLAB to execute the
commands all at once.
To open a new script le, you can either
type edit at the command prompt or
Click on the icon or
Press Ctrl + N.
Tan Do (VGU) Programming for engineers Lecture 3 20 / 27
struct arrays
In the script le, type in all the information of the structure array (see gure).
Then save the script le under some name, say StudentDatabase.m (note the extension is .m).
To run this script le, in MATLAB type
» StudentDatabase
» student
student =
1x2 struct array with fields:
name
SSN
email
tests
Tan Do (VGU) Programming for engineers Lecture 3 21 / 27
struct arrays
Accessing and modifying structures
To access a eld in a structure, for example, suppose we want to see John
Smith's second test score, use
» student(1).tests(2)
ans =
75
If we want to change John Smith's second test score from 75 to 80, type
» student(1).tests(2) = 80;
Tan Do (VGU) Programming for engineers Lecture 3 22 / 27
struct arrays
Next suppose we want to add phone numbers to the database, i.e., to add
an extra eld in a structure. Then we type
» student(1).phone = ’090758232’
All other structures will now have a phone eld. These elds will contain
the empty array until you give them values.
To remove a eld from every structure in an array, for example, we want to
remove SSN from the database, use
» new_student = rmfield(student,’SSN’);
Tan Do (VGU) Programming for engineers Lecture 3 23 / 27
cell arrays
Cell arrays - Some terminology
A cell array is an array in which every element is a cell which can contain an array.
We can store dierent classes of arrays in a cell array.
To assign data to each cell in a cell array, we can use either cell indexing or
content indexing.
Example Let A be a cell array whose cells contain the location, the date, the air
temperature (measured at 8 am, 12 noon and 5 pm) and the water temperature
measured at the same time in three dierent points in a pond.
Walden Pond August 20, 2017
h i 55 57 56
60 72 65 54 56 55
52 55 53
Tan Do (VGU) Programming for engineers Lecture 3 24 / 27
cell arrays
To use cell indexing method, in a script le, type
A(1,1) = {’Waldon Pond’};
A(1,2) = {’August 20, 2017’};
A(2,1) = {[60, 71, 65]};
A(2,2) = {[55, 57, 56; 54, 56, 55; 52, 55, 53]};
To use content indexing method, in a script le, type
A{1,1} = ’Waldon Pond’;
A{1,2} = ’August 20, 2017’;
A{2,1} = [60, 71, 65];
A{2,2} = [55, 57, 56; 54, 56, 55; 52, 55, 53];
Type A at the command line to see
A =
’Walden Pond’ ’August 20, 2017
[1 × 3 double] [3 × 3 double]
To see the whole content of the cell array, type
» celldisp(A)
Tan Do (VGU) Programming for engineers Lecture 3 25 / 27
cell arrays
cell function and accessing cell array
The cell function is used to create a cell array of a specied size.
For example,
» C = cell(3,2)
creates the 3 × 2 cell array C whose cells are empty arrays.
We can then enter contents into the cells using the assignment operator.
» C(1,1) = {[2, 9, 7]};
» C(1,2) = {’Nice day!’};
We can accessing the contents of a cell array using either cell indexing or content
indexing.
» v = C(1,1) % cell indexing
assigns cell C(1,1) to the variable v. Thus v itself is a cell.
» class(v)
ans =
cell
Tan Do (VGU) Programming for engineers Lecture 3 26 / 27
cell arrays
On the other hand,
» w = C{1,1} % content indexing
assigns the content of cell C(1,1) to the variable w.
Thus w itself is a 1 × 3 vector of type double.
» class(w)
ans =
double
» C{1,1}(2)
ans =
9
Tan Do (VGU) Programming for engineers Lecture 3 27 / 27