You are on page 1of 53

MATLAB

INTRODUCTION
• In this part, you will learn how to use the
MATLAB command prompt for performing
calculations and creating variables.
• To help you familiarize with the basics of
the MATLAB interface.
• To help you work with lists of numbers,
practice constructing and manipulating
lists of vectors, and matrices.
• Introduce you to programming, and how
to define variables, store values in
variables, and changing the values of
variables.
• DEFINITIONS:
• The name MATLAB stands for matrix
laboratory
• MATLAB is a high-performance
language for computation,
visualization, and programming in an
easy-to-use environment where
problems and solutions are expressed
in familiar mathematical notation.
• MATLAB allows you to solve many
technical computational problems,
especially those with matrix and vector
formulations.
• MATLAB was developed by the LINPACK
and EISPACK projects to provide easy
access to matrix software.
• In academic environment, it is the
standard instructional tool for
introductory and advanced courses
in mathematics, engineering, and
science.
• In industry, MATLAB is the tool of
choice for high-productivity research,
development, and analysis.
• MATLAB features a family of add-on
application called toolboxes that
allow you to learn and apply
specialized technology.
• Toolboxes are comprehensive
collections of MATLAB functions (M-
files) that extend the MATLAB
environment to solve particular
classes of problems.
• Many of these tools are graphical
user interfaces.
• It includes the MATLAB desktop and
Command Window, a command
history, an editor and debugger, a
code analyzer and other reports, and
browsers for viewing help, the
workspace, files, and the search
path.
The Basics: What is Programming
• Every computer is a machine. It
neither thinks nor understands. It
does exactly what you want it to do
but it must be told what to do,
explicitly in its language.
• In this course we are discussing the
MATLAB® syntax.
• When you run MATLAB for the first time,
The Desktop is the 1st thing you will see. In
it you will see windows with names like
Workspace, Command History, Command
Window, and launch Pad. The important
one for now is the "Command Window."
To close all the others, open the "Desktop"
menu and unselect all selected options,
except for "Command Window.“
• You should have now, a single frame,
which is white, except for ">>" and, a
blinking cursor.
Numbers
• MATLAB uses conventional decimal
notation, with an optional decimal
point and leading plus or minus sign,
for numbers. Scientific notation uses
the letter e to specify a power-of-ten
scale factor. Imaginary numbers use
either i or j as a suffix. Some examples
of legal numbers are
• 3 -79 0.0021
• 5.4587268 2.73210e-20 5.00542e23
• 1i -3.14159j 3e5i
• Operators
• Expressions use familiar arithmetic
operators and precedence rules.
• + Addition
• - Subtraction
• * Multiplication
• / Division
• \ Left division(It performs the inverse
of a division i.e ( 12/4 )-1 can be written as
12\4)
• ^ Power
• ' Complex conjugate transpose
• ( ) Specify evaluation order
Functions

• MATLAB provides a large number of


standard elementary mathematical
functions, including abs, sqrt, exp, and
sin.
• Taking the square root or logarithm of a
negative number is not an error; the
appropriate complex result is produced
automatically.
• MATLAB also provides many more
advanced mathematical functions,
including Bessel and gamma functions.
• Most of these functions accept complex
arguments.
• To display a list of the elementary,
mathematical functions, type help elfun
• For a list of more advanced
mathematical and matrix functions,
type help specfun or help elmat
Command Prompt and Expressions
• MATLAB® is a big calculator.
• To calculate something simply type it in
at the "command prompt" and press
Enter.
• Example: Calculate 1 + 1
• Simply type it in and press Enter. The
screen should show:
• >> 1+1
• ans =
• 2
• meaning that the answer is 2.
• Exercise 1. Run MATLAB, find the
command window and the blinking
cursor.
• Find the answer to the following
arithmetic problems:
• 1234+4321=?
• 104−765=?
• 47∗33=?
• 3 ^4 =? (The operator for "power" is the
circumflex ^, usually found by pressing
Shift ⇑ 6
• How far is 19^2 from its approximation
20 ^2 −2∗20
• Find an approximation to 1/73
• Find the square root of 31
• If two sides of a right triangle have
lengths 31 and 45, what is the length of
the hypotenuse?
• Ask MATLAB for the value of π
• You may have noticed in the exercises
that the answer is only given with 5
digits of accuracy.
• Internally, MATLAB keeps a 16 (more-
or-less) digit version of the number it
shows us, but to keep things orderly, it
only displays the answer rounded to
show 5 digits (by default).
• We can change this by issuing a
command:
• >> format long
• >> pi
• ans = 3.141592653589793
• We can see this, by subtracting part of
π from ans, which always holds the full,
unrounded answer to the previous,
unassigned expression:
• Exercise 2. Remember the cosine rule?
c^2 = a^2 + b^2 −2abcos(θ). Find the
length of the hypotenuse of a triangle
with angle 30ο, and sides with lengths
10 and 20. The MATLAB trigonometric
functions (cos, sin, tan) use radians, so
you will need to convert using π
• Recall that pi radian = 180 degrees.
• >> format short
• >> pi
• ans =
3.1416
>> ans-3.1415
ans = 9.2654e-05
>> ans - 9.2653e-5
ans =
5.8979e-10
• The expression would look like this:
• >> a=10
• a=10
• >>b=20
• b=20
• c =sqrt(a^2+b^2-2*a*b*cos(pi/6))
Although the default MATLAB funs (cos,
sin and tan) use radians, we could still
solve the given problem directly:
• c =sqrt(a^2+b^2-2*a*b*cosd(30))
• Lists, Vectors, and Matrices
• MATLAB® is very convenient at
calculating with lists of numbers. It was
actually built for manipulating two-
dimensional lists called matrices. An n-
by-m matrix has n rows and m columns
of numbers, and many MATLAB
commands know how to work correctly
and efficiently with them.
Example 1
>> sum([10 11 12 13 14 15 16 17 18 19
20])
ans =
165
• Example 2
• >> sum([10 12 14 16 18 20 22 24 26 28])
• ans =
• 190
• Here we used a function sum and its
argument was a (row) vector we
created "manually". But we could
have created the vectors by using
shorthand notation.
• Comments
• The colon (:) which is one of the most
important MATLAB operators, helps us
to list numbers.
• The expression 1:10 is a row vector
containing the integers from 1 to 10:
• Example: >> 1:10
• ans =
• 1 2 3 4 5 6 7 8 9 10
• Example 1 could have been written:
• sum(n:m). Note that the list was
increasing (step =1): where n=10 and
m=20. m must be greater than n.
• >> sum(10:20)
• ans =
• 165
• In example 2: the list was increasing
(step =2) hence it would be written as
• Sum(n:s:m)
were n=10, m=28 and (incremental step
is s=2)
• >> sum(10:2:28)
• ans =
• 190
• To obtain non unit spacing, specify an
increment. We could also use step-size
< 1. For example, 100:-7:50 is 100 93
86 79 72 65 58 51 and
• 0: pi/4:pi is 0 0.7854 1.5708
2.3562 3.1416.
• >> sum(4:0.1:5)
• ans =
• 49.5000
• >> sum(5:-2:-2)
• ans =
• 8
• To write a column vector use the semicolons(;)
• [4 ; 3; 7]
• >>[4;3;7]
• ans =
• 4
• 3
• 7
• You could find the transpose of a column
vector: e.g (n:m)’ to give a row vector
• find
• >> [4;3;7]‘
• ans =
• 4 3 7
• A colon(:) gives a row vector, semicolon (;)
gives a column vector. While the transpose
of column vector gives a row, the
transpose of a row vector gives column.
• Do the following practice exercises:
1. Try out sequences with step-size <1 :
[5:0.1:6], [6:-3:-6].
2. Create a list of the whole numbers between
21 and 30 (inclusive), find their sum
3.Create the vector of the previous question in
decreasing order.
4.Find the sum of the odd numbers between 100
and 200.
1. Try out sequences with step-size <1 : [5:0.1:6], [6:-3:-6].
• >> [5:0.1:6]
• ans =
• 5.0000 5.1000 5.2000 5.3000 5.4000 5.5000 5.6000 5.7000
5.8000 5.9000 6.0000
• >> [6:-3:-6]
• ans =
• 6 3 0 -3 -6
• Notice that square brackets are used.
• Finding their transpose gives
• [6:-3:-6]‘
• ans =
• 6
• 3
• 0
• -3
• -6
2. Create a list of the whole numbers between 21 and 30 (inclusive), find their
sum and transpose
• [21:30] or (21:30)
• ans =
• 21 22 23 24 25 26 27 28 29 30
• >> sum(21:30) pls notice that >> sum[21:30] will not work.
• ans =
• 255
• >> [21:30]‘
• ans =
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29
• 30
3.Create the vector of the previous question in decreasing order. [21:30] or
(21:30) now becomes (30:-1:21)
>> (30:-1:21)
ans =
30 29 28 27 26 25 24 23 22 21
The transpose is:
>> (30:-1:21)‘
ans =
30
29
28
27
26
25
24
23
22
21
4. List and find the sum of the odd
numbers between 100 and 200.
• >> sum(100:200)
• ans =
• 15150
• Variables
• Often, a result of some calculation is
needed for later use, or perhaps a
complicated expression can be examined
more carefully if done in parts:
• Use of “variables” helps us to perform both: A
Variable holds whatever input is assigned them
by the use of the equal sign (=):
• x=2 creates a variable called "x" and stores the
value “2" in it. If one then types "x" in an
expression, MATLAB® will use the value stored in
"x", i.e., “2".
• One can define variables to hold anything that
MATLAB can calculate.
• You can easily overwrite a variable with a new
assignment: x=4 now the variable x "contains"
the value “4".
• One can use x as part of an expression:
x^2+x-cos(x)
• Or to create a new variable: y= x^2+7
• A variable can be a vector (or matrix):
e.g
• A=[1 2 3 4]
• A=
• 1 2 3 4
• One can change just a part of A: A(3)= 0
• >> A(3)=0
• A=
• 1 2 0 4
• Note that you can "hide" important
MATLAB functions and constants by
defining a variable with the same
name: pi=3 will give interesting results
later (to remove clear pi).
• This is usually not a good idea, so take care before
using a nice name like sum, exp, or det, as these are
all built-in functions. You can check if a variable is
already in use by using the which command:
• >> which exp
• built-in (C:\Program
Files\MATLAB\R2007b\toolbox\matlab\elfun\@doub
le\exp) % double method
• >> which det
• built-in (C:\Program
Files\MATLAB\R2007b\toolbox\matlab\matfun\@sin
gle\det) % single method
• >> which sun
• 'sun' not found.
• >> which pi
• built-in (C:\Program
Files\MATLAB\R2007b\toolbox\matlab\el
mat\pi)
• >> which Pi
• 'Pi' not found.
• The difference is in capitalization. .
MATLAB-defined functions will always use
lower-case names.
• So avoid collision by capitalizing the first
letter of your variable and functions
names.
• Practice problems:
• Create the list of numbers from 3 to 10
• Create the list of even numbers from –20 to 20
• Create the decreasing list of numbers from 100
to 90
• >> (3:10)
• ans =
• 3 4 5 6 7 8 9 10
• >> (-20:2:20)
• ans =
-20 -18 -16 -14 -12 -10 -8 -6 -4 -2 0
2 4 6 8 10 12 14 16 18 20
• >> (100:-1:90)
• ans =
• 100 99 98 97 96 95 94 93 92 91
90
• There's one special variable: It is the
ans variable: It holds the last calculated
value that was not placed into a
variable. When a command given to
MATLAB® returns a value that you
realize is important, but forgot to
assign into a variable, you then assign a
variable equating it to ‘ans’
• >> sin(pi/2)
• ans =
• 1
• You can save the "return value" in the
variable x
• >> x=ans
• x=
• 1
• Now x holds the answer, 1
• ROOT-FINDING
• Using MATLAB to find the roots of
equations, and specifically, nonlinear
equations. Newton's method will be
used for this process, and step through
multiple iterations of Newton’s method
in order to arrive at a final solution.
• Newton's Method
• Many mathematical problems involve
solving equations. While linear eqns can be
solved rather easily, nonlinear ones cannot.
Let a nonlinear equation be defd as
• f(x)=0
For example, find x if tanh(x)=x/3.
You re-write as f(x)=tanh(x)−x/3 =0. Then
finding solutions to the eqn is called "root-
finding" (a "root“ gives a value of x for
which the equation is satisfied).
• Newton's method is an iterative method for
finding an approximation to the root. After
several iterations of this, one is left with an
approximation that can be as good as you like
(you are also limited by the accuracy of the
computation using ordinary calculator but in
the case of MATLAB®, it is 16 digits.
• By Iterative methods we mean doing the
exact same thing over and over again. It can
be very tedious when it is done manually but
it is perfect for a computer.
• Newton's method is an iterative
process. So we will learn how to
construct two types of logical loops:
These loops will be useful tools not just
for the purpose of using Newton's
method, but also for future use in
writing code that can handle more
complicated operations. In addition, We
will be introduced to plotting in MATLAB
and saving code in a file for future or
frequent use.
• The Newton’s formula is:
• xn+1 = xn − f(xn)/f′(xn)
• We evaluate both the function f(x) and the
derivative, f′(xn) at xn.
• A problem may arise if the derivative is not
known or complicated to compute, but there
are other methods we could use in that case.
• For example, we look at a function for which
there is no formula for the solution:
• f(x)=tanh(x)−x/3
• f(x)’ = tanh′(x) –(x/3)’=1+cosh2(x) -1/3
= sech2(x) – 1/3,
Hence from the Newton formula we have:
• xn+1 = xn −(tanh(xn)−xn/3)/(sech(xn)^2−1/3).
• We can do this manually by starting somewhere (not
zero):
• >> x=2
• x=
• 2
• >> x=x-(tanh(x)-x/3)/(sech(x)^2-1/3)
• x=
• 3.1320
• >> x=2
• x=
• 2
• >> x=x-(tanh(x)-x/3)/(sech(x)^2-1/3)
• x=
• 3.1320 use the arrow key to retype the eqn many times.
• >> x=x-(tanh(x)-x/3)/(sech(x)^2-1/3)
• x=
• 2.9853
• >> x=x-(tanh(x)-x/3)/(sech(x)^2-1/3)
• x=
• 2.9847
• >> x=x-(tanh(x)-x/3)/(sech(x)^2-1/3)
• x=
• 2.9847

You might also like