KEMBAR78
Lecture 02 | PDF | Matrix (Mathematics) | Matlab
0% found this document useful (0 votes)
11 views69 pages

Lecture 02

This document provides an introduction to using MATLAB for simulating and analyzing data, specifically in the context of modeling examples. It covers the MATLAB environment, including command, graphics, and edit windows, and explains how to perform mathematical operations, assignments, and create arrays, vectors, and matrices. Additionally, it discusses built-in functions, the colon operator, and character strings, emphasizing hands-on practice for proficiency.

Uploaded by

olajuwonsinclair
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views69 pages

Lecture 02

This document provides an introduction to using MATLAB for simulating and analyzing data, specifically in the context of modeling examples. It covers the MATLAB environment, including command, graphics, and edit windows, and explains how to perform mathematical operations, assignments, and create arrays, vectors, and matrices. Additionally, it discusses built-in functions, the colon operator, and character strings, emphasizing hands-on practice for proficiency.

Uploaded by

olajuwonsinclair
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

• In this section, we will learn how

MATLAB can be used to


simulate and analyse such data as
obtained in the modelling
examples presented in the
LESSON 2: •
previous sections.
Beyond showing how MATLAB
can be employed to compute
MATLAB quantities like velocity, drag
coefficients, h/r, angle of
elevation, θ etc.
FUNDAMENTALS • We will also illustrate how its
graphical capabilities provide
additional insight into such
analyses.
◼ A Problem in FOCUS
◼ The MATLAB environment
◼ Assignment
CONTENTS ◼ Mathematical operations
◼ Use of built-in functions
◼ Graphics
◼ Other resources
◼ In Section 1.2.1, we used a force balance
to determine the terminal velocity of a
free-falling object like a bungee jumper.

A Problem in
Focus ◼ where vt = terminal velocity (m/s), g =
gravitational acceleration (m/s2), m = mass
(kg), and cd = a drag coefficient (kg/m).
◼ Aside from predicting the terminal
velocity, this equation can also be
rearranged to compute the drag
coefficient.
(1.28)

◼ Thus, if we measure the terminal velocity


of a few jumpers of known mass, this
equation provides a means to estimate the
A Problem in drag coefficient.
Focus ◼ The data in Table 1.2 were collected for
this purpose.

TABLE 1.2 Data for the mass and associated terminal velocities of a few jumpers.
◼ MATLAB is a computer program that
provides the user with a convenient
environment for performing many types
of calculations.
◼ In particular, it provides a very nice tool
The MATLAB to implement numerical methods.
Environment ◼ The most common way to operate
MATLAB is by entering commands one at
a time in the command window. ,
◼ In this section, we use this interactive or
calculator mode to introduce you to
common operations such as performing
calculations and creating plots.
◼ In the next Section, we show how such
commands can be used to create
MATLAB programs.
◼ One further note. This section has been
The MATLAB written as a hands-on exercise. That is,
you should read it while sitting in front of
Environment
your computer.
◼ The most efficient way to become
proficient is to actually implement the
commands on MATLAB as you proceed
through the following material.
◼ MATLAB uses three primary windows:
Command window - used to enter
commands and data.
Graphics window - used to display plots
The MATLAB and graphs.
Environment Edit window - used to create and edit
M-files.
◼ In this section, we will make use of the
command and graphics windows. In the
next Section, we will use the edit window
to create M-files.
◼ After starting MATLAB, the command
window will open with the command
prompt being displayed:
>>
The MATLAB ◼ The calculator mode of MATLAB
Environment operates in a sequential fashion as you
type in commands line by line.
◼ For each command, you get a result.
◼ Thus, you can think of it as operating like
a very fancy calculator.
◼ For example, if you type in:
>> 55 – 16
◼ MATLAB will display the result:
ans =
The MATLAB 39
Environment ◼ Notice that MATLAB has automatically
assigned the answer to a variable, ans.
◼ Thus, you could now use ans in a
subsequent calculation:
>> ans + 11
with the result
ans =
50
◼ MATLAB assigns the result to ans
whenever you do not explicitly
The MATLAB assign the calculation to a variable
Environment of your own choosing.
◼ Assignment refers to assigning values to
variable names.
◼ This results in the storage of the values in
the memory location corresponding to
the variable name.
(a) Scalars
Assignment
◼ Try typing
>> a = 4
◼ Note how the assignment echo prints to
confirm what you have done:
a=
4
◼ Echo printing is a characteristic of
MATLAB. It can be suppressed by
terminating the command line with the
semicolon (;) character. Try typing
>> A = 6;
Assignment ◼ You can type several commands on the
same line by separating them with
commas or semicolons.
◼ If you separate them with commas, they
will be displayed, and if you use the
semicolon, they will not.
◼ For example,
>> a = 4, A = 6;x = 1;
a=
4
◼ MATLAB treats names in a case-sensitive
Assignment manner - that is, the variable a is not the
same as A.
◼ To illustrate this, enter
>> a
◼ and then enter
>> A
◼ See how their values are distinct. They are
distinct names.
◼ We can assign complex values to variables
since MATLAB handles complex arithmetic
automatically.
◼ The unit imaginary number √-1 is
Assignment preassigned to the variable i.
◼ Consequently, a complex value can be
assigned simply as in
>> x = 2+i*4
x=
2.0000 + 4.0000i
◼ It should be noted that MATLAB allows the
symbol j to be used to represent the unit
imaginary number for input. However, it
always uses an i for display. For example,
>> x = 2+j*4
x=
Assignment
2.0000 + 4.0000i
◼ There are several predefined variables, for
example, pi.
>> pi
ans =
3.1416
◼ Notice how MATLAB displays four decimal
places. If you desire additional precision,
enter the following:
>> format long
◼ Now when pi is entered the result is
displayed to 15 significant figures:
Assignment
>> pi
ans =
3.14159265358979
◼ To return to the four-decimal version, type
>> format short
◼ The following is a summary of the format
commands you will employ routinely in
engineering and scientific calculations. They
all have the syntax: format type.

Assignment
(b) Arrays, Vectors and Matrices
◼ An array is a collection of values that are
represented by a single variable name.
One-dimensional arrays are called vectors
and two-dimensional arrays are called
matrices.
Assignment ◼ The scalars used in Section 2.2.1 are
actually matrices with one row and one
column.
◼ Brackets are used to enter arrays in the
command mode.
◼ For example, a row vector can be assigned
as follows:
>> a = [1 2 3 4 5]
a=
12345
◼ Note that this assignment overrides the
previous assignment of a = 4.
Assignment ◼ In practice, row vectors are rarely used to
solve mathematical problems.
◼ When we speak of vectors, we usually
refer to column vectors, which are more
commonly used.
◼ A column vector can be entered in several
ways. Try them.
>> b = [2;4;6;8;10]
◼ or
>> b = [2
4
6
Assignment 8
10]
◼ or, by transposing a row vector with the '
operator,
>> b = [2 4 6 8 10]'
◼ The result in all three cases will be
b=
2
4
6
Assignment 8
10
◼ A matrix of values can be assigned as
follows:
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
123
456
789
◼ In addition, the Enter key (carriage return)
Assignment can be used to separate the rows. For
example, in the following case, the Enter
key would be struck after the 3, the 6 and
the ] to assign the matrix:
>> A = [1 2 3
456
7 8 9]
◼ Finally, we could construct the same matrix
by concatenating (i.e., joining) the vectors
representing each column:
>> A = [[1 4 7]’, [2 5 8]’, [3 6 9]']
◼ At any point in a session, a list of all
current variables can be obtained by
Assignment entering the who command:
>> who
Your variables are:
A a ans b x

or, with more detail, enter the whos command:


>> whos
Name Size
A 3x3
a 1x5 Bytes Class
ans 1x1 72 double array
b 5x1
x 1x1
40 double array
40 double array
double array
16
(complex)
Assignment ◼ Grand total is 21 elements using 176 bytes
◼ Note that subscript notation can be used
to access an individual element of an array.
◼ For example, the fourth element of the
column vector b can be displayed as
>> b(4)
ans =
8
◼ For an array, A(m, n) selects the element
in mth row and the nth column. For
example,

Assignment >> A(2,3)


ans =
6
◼ There are several built-in functions that can
be used to create matrices.
◼ For example, the ones and zeros functions
create vectors or matrices filled with ones
◼ Both have two arguments, the first for the
number of rows and the second for
number of columns.
◼ For example, to create a 2 × 3 matrix of
zeros:
>> E = zeros(2,3)
Assignment
E=
000
000
◼ Similarly, the ones function can be used to
create a row vector of ones:
>> u = ones(1,3)
u=
111
(c) The Colon Operator
◼ The colon operator is a powerful tool for
creating and manipulating arrays.
Assignment ◼ If a colon is used to separate two numbers,
MATLAB generates the numbers between
them using an increment of one:
>> t = 1:5
t=
12345
◼ If colons are used to separate three
numbers, MATLAB generates the numbers
between the first and third numbers using
an increment equal to the second number:
>> t = 1:0.5:3
t=
Assignment
1.0000 1.5000 2.0000 2.5000 3.0000
◼ Note that negative increments can also be
used
>> t = 10:-1:5
t=
10 9 8 7 6 5
◼ Aside from creating series of numbers, the
colon can also be used as a wildcard to
select the individual rows and columns of a
matrix.
◼ When a colon is used in place of a specific
subscript, the colon represents the entire
Assignment row or column.
◼ For example, the second row of the matrix
A can be selected as in
>> A(2, :)
ans =
456
◼ We can also use the colon notation to
selectively extract a series of elements
from within an array.
◼ For example, based on the previous
definition of the vector t:
>> t(2:4)
Assignment
ans =
987
t=
10 9 8 7 6 5
◼ Thus, the second through the fourth
elements are returned.
(d)The linspace and logspace
Functions
◼ The linspace and logspace functions
provide other handy tools to generate
vectors of spaced points.
Assignment ◼ The linspace function generates a row
vector of equally spaced points. It has the
form:
>> linspace(x1, x2, n)
◼ which generates n points between x1 and
x2. For example,
>> linspace(0,1,6)
ans =
0 0.2000 0.4000 0.6000 0.8000 1.0000
◼ If the n is omitted, the function
automatically generates 100 points.
◼ The logspace function generates a row
Assignment vector that is logarithmically equally
spaced. It has the form
>> logspace(x1, x2, n)
which generates n logarithmically equally
spaced points between decades 10x1 and
10x2. For example,
>> logspace(-1,2,4)
ans =
0.1000 1.0000 10.0000 100.0000
◼ If n is omitted, it automatically generates
50 points.
(e) Character Strings
Assignment ◼ Aside from numbers, alphanumeric
information or character strings can be
represented by enclosing the strings
within single quotation marks. For
example,
>> f = 'Miles ';
>> s = 'Davis';
◼ Each character in a string is one element
in an array.
◼ Thus, we can concatenate (i.e., paste
together) strings as in
>> x = [f s]
x =
Assignment
Miles Davis
◼ Note that very long lines can be continued
by placing an ellipsis (three consecutive
periods) at the end of the line to be
continued.
◼ For example, a row vector could be
entered as
>> a = [1 2 3 4 5 ...
6 7 8]
a=
12345678
◼ However, you cannot use an ellipsis
Assignment within single quotes to continue a string.
◼ To enter a string that extends beyond a
single line, piece together shorter strings
as in
>> quote = ['Any fool can make a rule,' ...
' and any fool will mind it']
quote =
Any fool can make a rule, and any fool
will mind it

Assignment
◼ Operations with scalar quantities are
handled in a straightforward manner,
similar to other computer languages.
◼ The common operators, in order of
priority, are
Mathematical
Operations

◼ These operators will work in calculator


fashion. Try
>> 2*pi
ans =
6.2832
◼ Also, scalar real variables can be included:
Mathematical >> y = pi/4;
Operations >> y ^ 2.45
ans =
0.5533
◼ Results of calculations can be assigned to
a variable, as in the next-to-last example,
or simply displayed, as in the last example.
◼ As with other computer calculation, the
priority order can be overridden with
parentheses.
◼ For example, because exponentiation has
higher priority then negation, the
Mathematical following result would be obtained:
Operations >> y = -4 ^ 2
y=
-16
◼ Thus, 4 is first squared and then negated.
◼ Parentheses can be used to override the
priorities as in
>> y = (-4) ^ 2
y=
16
Mathematical
◼ Calculations can also involve complex
Operations
quantities. Here are some examples that
use the values of x (2 + 4i) and y (16)
defined previously:
>> 3 * x
ans =
6.0000 + 12.0000i
>> 1 / x
ans =
0.1000 - 0.2000i
>> x ^ 2

Mathematical ans =
Operations -12.0000 + 16.0000i
>> x + y
ans =
18.0000 + 4.0000i
◼ The real power of MATLAB is illustrated
in its ability to carry out vector-matrix
calculations. It is worth introducing some
examples here.
◼ The inner product of two vectors (dot
Mathematical product) can be calculated using the *
operator,
Operations
>> a * b
ans =
110
◼ and likewise, the outer product
>> b * a
ans =
2 4 6 8 10
4 8 12 16 20
6 12 18 24 30

Mathematical 8 16 24 32 40
Operations 10 20 30 40 50
◼ To further illustrate vector-matrix
multiplication, first redefine a and b:
>> a = [1 2 3];
And
>> b = [4 5 6]';
◼ Now, try
>> a * A
(A was given in the previous example – slide
22)
Mathematical ans =
Operations
30 36 42
◼ or
>> A * b
ans =
32
77
122
Mathematical
◼ Matrices cannot be multiplied if the inner
Operations
dimensions are unequal.
◼ Here is what happens when the
dimensions are not those required by the
operations. Try
>> A * a
◼ MATLAB automatically displays the error
message:
??? Error using ==> mtimes
Inner matrix dimensions must agree.
◼ Matrix-matrix multiplication is carried out
Mathematical
in likewise fashion:\
Operations
>> A * A
ans =
30 36 42
66 81 96
102 126 150
◼ Mixed operations with scalars are also
possible:
>> A/pi
ans =
Mathematical 0.3183 0.6366 0.9549
Operations
1.2732 1.5915 1.9099
2.2282 2.5465 2.8648
◼ We must always remember that MATLAB
will apply the simple arithmetic operators
in vector-matrix fashion if possible.
◼ At times, you will want to carry out
calculations item by item in a matrix or
vector. MATLAB provides for that too.
For example,
Mathematical >> A^2
Operations ans =
30 36 42
66 81 96
102 126 150
◼ results in matrix multiplication of A with
itself.
◼ What if you want to square each
element of A? That can be done with
>> A.^2
ans =
149
Mathematical
Operations 16 25 36
49 64 81
The (. ) preceding the ^ operator signifies that
the operation is to be carried out element by
element. The MATLAB manual calls these array
operations. They are also often referred to as
element-by-element operations.
◼ MATLAB and its Toolboxes have a rich
collection of built-in functions. You can
use online help to find out more about
them.
◼ For example, if you want to learn about
Use of Built-in the log function, type in
Functions >> help log
LOG Natural logarithm.
LOG(X) is the natural logarithm of the elements
of X.
Complex results are produced if X is not positive.
See also LOG2, LOG10, EXP, LOGM.
◼ For a list of all the elementary functions,
type
>> help elfun
◼ One of their important properties of
MATLAB’s built-in functions is that they
Use of Built-in will operate directly on vector and
Functions matrix quantities. For example, try
>> log(A)
ans =
0 0.6931 1.0986
1.3863 1.6094 1.7918
1.9459 2.0794 2.1972
◼ and you will see that the natural
logarithm function is applied in array
style, element by element, to the matrix
A.
◼ Most functions, such as sqrt, abs, sin,
Use of Built-in acos, tanh, and exp, operate in array
Functions fashion.
◼ Certain functions, such as exponential
and square root, have matrix definitions
also.
◼ MATLAB will evaluate the matrix version
when the letter m is appended to the
function name.
◼ Try
>> sqrtm(A)
ans =
0.4498 + 0.7623i 0.5526 + 0.2068i
Use of Built-in 0.6555 - 0.3487i
Functions
1.0185 + 0.0842i 1.2515 + 0.0228i
1.4844 - 0.0385i
1.5873 - 0.5940i 1.9503 - 0.1611i 2.3134
+ 0.2717i
◼ There are several functions for rounding.
◼ For example, suppose that we enter a
vector:
>> E = [-1.6 -1.5 -1.4 1.4 1.5 1.6];
◼ The round function rounds the elements
Use of Built-in of E to the nearest integers:
Functions >> round(E)
ans =
-2 -2 -1 1 2 2
◼ The ceil (short for ceiling) function
rounds to the nearest integers toward
infinity:
>> ceil(E)
ans =
-1 -1 -1 2 2 2
◼ The floor function rounds down to the
nearest integers toward minus infinity:
Use of Built-in
Functions >> floor(E)
ans =
-2 -2 -2 1 1 1
◼ A common use of functions is to evaluate
a formula for a series of arguments.
Recall that the velocity of a free-falling
bungee jumper can be computed with
[Eq. (1. 9)]:
Use of Built-in
Functions
◼ where v is velocity (m/s), g is the
acceleration due to gravity (9.81 m/s2), m
is mass (kg), cd is the drag coefficient
(kg/m), and t is time (s).
◼ Create a column vector t that contains
>> t = [0:2:20]'
t=
0
2
4
Use of Built-in 6

Functions 8
10
12
14
16
18
20
◼ Check the number of items in the t array
with the length function:
>> length(t)
ans =
11
Use of Built-in
Functions ◼ Assign values to the parameters:
>> g = 9.81; m = 68.1; cd = 0.25;
◼ MATLAB allows you to evaluate a
formula such as v = f (t), where the
formula is computed for each value of the
t array, and the result is assigned to a
corresponding position in the v array.
◼ For our case,
>> v = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);
v=
0
18.7292
33.1118
Use of Built-in
42.0762
Functions 46.9575
49.4214
50.6175
51.1871
51.4560
51.5823
51.6416
◼ MATLAB allows graphs to be created
quickly and conveniently. For example, to
create a graph of the t and v arrays from
the data above, enter
>> plot(t, v)
◼ The graph appears in the graphics
Graphics window and can be printed or
transferred via the clipboard to other
programs.
Graphics
◼ You can customize the graph a bit with
commands such as the following:
>> title('Plot of v versus t')
>> xlabel('Values of t')
>> ylabel('Values of v')
>> grid
Graphics
◼ The plot command displays a solid thin blue line
by default. If you want to plot each point with a
symbol, you can include a specifier enclosed in
single quotes in the plot function.
◼ Table 2.2 lists the available specifiers. For
example, if you want to use open circles enter
Graphics
>> plot(t, v, 'o')
◼ You can also combine several specifiers.
◼ For example, if you want to use square
green markers connected by green
dashed lines, you could enter
>> plot(t, v, 's--g')
◼ MATLAB allows you to display more than
one data set on the same plot. For example,
an alternative way to connect each data
marker with a straight line would be to type
>> plot(t, v, t, v, 'o')
◼ In contrast, the following commands would
Graphics result in both lines and symbols being
displayed:
>> plot(t, v)
>> hold on
>> plot(t, v, 'o')
>> hold off
◼ In addition to hold, another handy function is subplot, which allows
you to split the graph window into sub-windows or panes. It has
the syntax
>> subplot(m, n, p)
◼ This command breaks the graph window
into an m-by-n matrix of small axes, and
selects the p-th axes for the current plot.
We can demonstrate subplot by examining
MATLAB’s capability to generate three
Graphics dimensional plots. The simplest
manifestation of this capability is the plot3
command which has the syntax
>> plot3(x, y, z)
where x, y, and z are three vectors of the
same length. The result is a line in
three-dimensional space through the points
whose coordinates are the elements of x, y,
◼ Plotting a helix provides a nice example to
illustrate its utility. First, let’s graph a circle
with the two-dimensional plot function using
the parametric representation: x = sin(t) and
y = cos(t). We employ the subplot
command so we can subsequently add the
three-dimensional plot.
Graphics >> t = 0:pi/50:10*pi;
>> subplot(1,2,1);plot(sin(t),cos(t))
>> axis square
>> title('(a)')
◼ As in Fig. 2.1a, the result is a circle. Note that the circle
would have been distorted if we had not used the axis
square command.
◼ Now, let’s add the helix to the graph’s right
pane. To do this, we again employ a parametric
representation: x = sin(t), y = cos(t), and z = t
>> subplot(1,2,2);plot3(sin(t),cos(t),t);
>> title('(b)')
◼ The result is shown in Fig. 2.1b. Can you
visualize what’s going on? As time evolves, the x
Graphics and y coordinates sketch out the circumference
of the circle in the x–y plane in the same
fashion as the two-dimensional plot. However,
simultaneously, the curve rises vertically as the
z coordinate increases linearly with time. The
net result is the characteristic spring or spiral
staircase shape of the helix.
Graphics

FIGURE 1.6: A two-pane plot of (a) a two-dimensional circle and (b) a three-dimensional helix type.
◼ MATLAB package itself includes an extensive Help facility
that can be accessed by clicking on the Help menu in the
command window.
◼ This will provide you with a number of different options for
exploring and searching through MATLAB’s Help material. In
addition, it provides access to a number of instructive
demos.
◼ Help is also available in interactive mode by typing the help
Other command followed by the name of a command or function.
Resources ◼ If you do not know the name, you can use the lookfor
command to search the MATLAB Help files for occurrences
of text.
◼ For example, suppose that you want to find all the
commands and functions that relate to logarithms, you could
enter:
>> lookfor logarithm,
◼ and MATLAB will display all references that include the word
logarithm.

You might also like