KEMBAR78
MAT 213 Mathematical Computing 2019 | PDF | Trigonometric Functions | Matrix (Mathematics)
0% found this document useful (0 votes)
16 views38 pages

MAT 213 Mathematical Computing 2019

The document is a comprehensive guide on MATLAB, covering its basics, functionalities, and applications in mathematical computing. It includes sections on getting started, creating arrays and matrices, and programming in MATLAB, along with detailed explanations of commands, operations, and built-in functions. The document serves as a resource for both beginners and advanced users in mathematics, science, and engineering fields.

Uploaded by

shekedeganizani2
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)
16 views38 pages

MAT 213 Mathematical Computing 2019

The document is a comprehensive guide on MATLAB, covering its basics, functionalities, and applications in mathematical computing. It includes sections on getting started, creating arrays and matrices, and programming in MATLAB, along with detailed explanations of commands, operations, and built-in functions. The document serves as a resource for both beginners and advanced users in mathematics, science, and engineering fields.

Uploaded by

shekedeganizani2
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/ 38

MAT 213: MATHEMATICAL COMPUTING

E.S. MWANANDIYE
(MSc. Mathematics, BSc.)
Mathematical Sciences Department,
Chancellor College, University of Malawi

0.5

−0.5
40
30 40
20 30
20
10 10
0 0

November 4, 2019
Contents

Table of Contents . . . . . . . . . . . . . . . . . . . 1
1 MATLAB BASICS 2
1.1 Getting Started . . . . . . . . . . . . . . . . . 3
1.1.1 MATLAB Windows . . . . . . . . . . . 3
1.1.2 Working In The Command Window . . . 4
1.1.3 Arithmetic Operations with Scalars . . . 6
1.1.4 Display Formats . . . . . . . . . . . . . 7
1.1.5 Elementary Math Built-in Functions . . 8
1.1.6 Help and Documentation . . . . . . . . 8
1.2 Scalar Variables . . . . . . . . . . . . . . . . . 10
1.2.1 The Assignment Operator . . . . . . . . 11
1.2.2 Rules About Variables Names . . . . . . 13
1.2.3 Predefined Variables and Keywords . . . 13
1.2.4 Frequently Used Variables . . . . . . . . 14
1.2.5 Managing Variables . . . . . . . . . . . 14
1.3 Script Files . . . . . . . . . . . . . . . . . . . . 14
1.3.1 Notes About Script Files . . . . . . . . . 15
1.3.2 Creating and Saving a Script File . . . . 15
1.4 Application of MATLAB . . . . . . . . . . . . 17
2 CREATING ARRAYS AND MATRICES 20
2.1 Arrays . . . . . . . . . . . . . . . . . . . . . . 20
2.1.1 Creating Vectors . . . . . . . . . . . . . 20
2.1.2 Array from a Known list of numbers . . 21
2.1.3 The Colon Operator: Creating Vectors
with Constant Spacing . . . . . . . . . . 22
2.1.4 The linspace function: Creating Vector
with Equal (Linear) Spacing . . . . . . . 23
2.1.5 Random Numbers . . . . . . . . . . . . 24
2.1.6 Transposing Vectors . . . . . . . . . . . 24
2.1.7 Index or Subscripts . . . . . . . . . . . . 25
2.2 Creating Matrix Variables . . . . . . . . . . . . 27
2.2.1 Creating Matrix using Colon operator . . 28
2
2.2.2 Creating Matrices of Random numbers . 28
2.2.3 Matrix Transpose . . . . . . . . . . . . 29
2.2.4 Reffering to and Modifying Matrix Ele-
ments . . . . . . . . . . . . . . . . . . . 30
2.2.5 Functions on Matrices . . . . . . . . . . 31
2.2.6 Element-wise Operation on Matrices . . 33
3 Introduction to MATLAB Programming 35
3.1 Algorithms . . . . . . . . . . . . . . . . . . . . 35
3.2 MATLAB Scripts . . . . . . . . . . . . . . . . 36

1
MATLAB BASICS

• MATLAB is a powerful technical computing system for


handling scientific and engineering calculations.
– can be thought of as a super-powerul graphing calcu-
lator
• MATLAB is used for math computations, modelling and
simulations, data analysis and processing, visualization and
graphics, and algorithm development.
• In addition, it is a programming language
– MATLAB is an interpreted language, like Python, Ja-
va, C++, e.t.c.
– Commands are executed line-by-line
• MATLAB (MATtrix LABoratory) was designed to matrix
computation particularly easy.
– Its basic data element is a matrix (array).
• Widely used in universities and colleges in introductory
and advanced course in mathematics, sciences and engi-
neering.
• In industry the software is used in research, development
and design
– Computer Vision
– Machine Learning
– Deep Learning
• The standard MATLAB program has tools (functions) used
to solve common problems.
• MATLAB has optional toolboxes that are collections of
specialized programs designed to solve specific types of
problems.
– toolboxes for signal processing, symbolic calculations,
and control systems.
2
1.1 Getting Started
• Get MATLAB software installed on your Desktops, PCs,
or MacBooks.
• To start the program
– From Windows, double click the MATLAB icon on y-
our Windows desktop.
– From Unix, type matlab at the operating system promp-
t.
– From MacOS, open X11 (i.e., open an X-terminal win-
dow), then type matlab at the prompt.

1.1.1 MATLAB Windows


When the program starts, the MATLAB desktop window that
opens contains four windows (default) or five windows (when
Editor window is docked).

Figure 1.1:

1. Command Window
• main window that opens when MATLAB is started,
3
• Enters variables,
• Runs programs.
2. Editor Window
• Creates and debugs script and function files
3. Command History
• Logs commands entered in the Command Window
4. Workspace Window
• Provide information about the variables that are used.
5. Current Directory Window
• Shows the files in the current directory.
6. Figure Window
• Contains output from graphic commands
7. Help Window
• Provides help information.
8. Launch Pad Window
• Provides access to tools, demos, and documentation.
Starting MATLAB automatically creates a folder named ”MAT-
LAB” in the user’s Document Folder.
• It is default working folder.
• Anything saved from the Command Window will be saved
in this folder.

1.1.2 Working In The Command Window


• To type a command, the cursor must be placed next to the
command prompt (>>)
• Once a command is typed and Enter key is pressed, the
command is executed. However, only the last command is
executed. Everything executed previously is unchanged.
4
• Several commands can be typed in the same line. This is
doen by typing a comma between the commands. When
Enter key is pressed, the commands are executed in order
from left to right.
• It is not possible to go back to a previous line in the Com-
mand Window, make a correction, and then re-executed
the command.
• A previously type command can be recalled to the com-
mand prompt with the up-arrow key (N). When the com-
mand is displayed at the command prompt, it can be modi-
fied if needed and executed. The down-key (H) can be used
to move down the previously type commands.
• If a command is too long to fit in one line, it can be con-
tinues to the next line by typing three periods (...), called
ellipsis and pressing the Enter key. The continuation of
the command is then typed in the new line. The command
can continue line after line to a total of 4096 characters.
• You can quit at any time with one of the following ways
– Click the X (close button) in the upper right-hand cor-
ner of the MATLAB desktop.
– Type quit or exit at the Command Window prompt
followed by pressing the Enter key.
The semicolon (;) suppresses command output
• if the semicolon (;) is typed at the end of a command, the
output of the command is not display
• Semicolon is useful when the result is obvious or known ,
or when the output is very large.
• If several commands are typed in the same line, the out-
put from any of the commands will not be displayed if
a semicolon is typed between the commands instead of a
comma.
Typing % designates a line as a comment
• Comment line is not executed when Enter key is pressed.
5
• The % character followed by text (comment) can also be
typed after a command (in the same line). This has no
effect on the execution of command.
• Comments are frequently used in programs to add descrip-
tions, or to explain the program
The clc command clears the Command Window
• The command does not does not change anything that was
done before. For example, if some variables were defined
previously, they still exist and can be used.

1.1.3 Arithmetic Operations with Scalars


Type 2 + 3 after the >> prompt, followed by Enter key as
indicated by < Enter >:
• >> 2 + 3 < Enter >
Next try this
• >> 3 − 2 < Enter >
• >> 2 ∗ 3 < Enter >
• >> 1/2 < Enter >
• >> 23 < Enter >
• >> 2\11 < Enter >
Operation Symbol Example
Addition + 5+6
Subtraction - 5-3
Multiplication * 5*3
Right Division / 5/3
Left Division \ 5\3 = 3/5

Exponentiation 53 (means 53 = 125)
MATLAB executes the calculation according to the order of
precedence displayed below.
6
Precedence Mathematical Operation
First Parentheses, where the innermost are executed first.
Second Exponentiation
Third Multiplication, division (equal precedence).
Fourth Addition and Subtraction.

1.1.4 Display Formats


MATLAB has several formats for displaying numbers. Details
of other formats can be obtained by typing help format in
the Command Window. The table below provides some of the
formats
Command Description
format short Fixed-point with 4 decimal digits for 0.001 ≤ x ≤ 1000.
Otherwise display format short e
format long Fixed-point with 15 decimal digits for 0.001 ≤ x ≤ 1000.
Otherwise display format long e
format short e Scientific notation with 4 decimal digits
format long e Scientific notation with 15 decimal digits
format short g Best of 5-digit fixed or floating point
format long g Best of 15-digit fixed or floating point
format bank Two decimal digits
format compact Eliminates blank lines to allow more lines with information
displayed on the screen.
format loose Adds blank lines (opposite of compact)

>> format short


>> 290/7
ans =
41.4286
>> format long
>> 290/7
ans =
41.428571428571421
>> format short e
>> 290/7
ans =
4.1429e+001
>> format long e
>> 290/7
ans =
4.142857142857143e+01
>> format short g
>> 290/7
7
ans =
41.429
>> format long g
>> 290/7
ans =
41.4285714285714
>> format bank
>> 290/7
ans =
41.43
>> format compact
>> 290/7
ans =
41.43
>> format loose
>> 290/7
ans =
41.43

1.1.5 Elementary Math Built-in Functions


In addition to basic operations, expression in MATLAB can
include functions. MATLAB has a very large library of built-
in functions.
• A function has a name and an argument in parentheses.
• e.g. A function that calculates the square root of a number
is sqrt(x). Its name is sqrt and the argument is x
• The argument can be a number, a variable that has been
assigned a numerical value, or a computable expression
that can be made up of numbers and/or variables.
• Function can also be included in arguments, as well as in
expressions.
The hyperbolic trigonometric functions are sinh(x), cosh(x), tanh(x), coth(x).

1.1.6 Help and Documentation


• >>help
– The most important command for learning MATLAB
on your own.
8
Function Description Example
sqrt(x) Square root. >> sqrt(81)
ans =
9
nthroot(x,n) Real nth root of a real number x. >> nthroot(80,5)
(If x is negative, n must be n odd integer). ans =
2.4022
exp(x) Exponential (ex ). >> exp(5)
ans =
148.4132
abs(x) Absolute Value. >> abs(-24)
ans =
24
log(x) Natural Logarith. Base e logarithm (ln). >> log(1000)
ans =
6.9078
log10(x) Base 10 logarithm. >> log10(1000)
ans =
3.000
factorial(x) The factorial function x!. >> factorial(5)
(x must be a positive integer). ans =
120

Table 1.1: Elementary Math Function

9
Function Description Example
sin(x) Sine of angle x (x in radians). >> sin(pi/6)
sind(x) Sine of angle x (x in degrees) ans =
0.5000
cos(x) Cosine of angle x (x in radians). >> cosd(30)
cosd(x) Cosine of angle x (x in degrees). ans =
0.8660
tan(x) Tangent of angle x (x in radians)
tand(x) Tangent of angle x (x in degrees)
cot(x) Cotangent of angle x (x in radians)
cotd(x) Cotangent of angle x (x in degrees)
asin(x) Inverse sine of angle x in radians
asind(x) Inverse sine of angle x in degrees
acos(x) Inverse cosine of angle x in radians
acosd(x) Inverse cosine of angle x in degrees
atan(x) Inverse tangent of angle x in radians
atand(x) Inverse tangent of angle x in degrees
acot(x) Inverse cotangent of angle x in radians
acotd(x) Inverse cotangent of angle x in degrees

Table 1.2: Trigonometric math functions

• To get information on how to use a function


– >>help sin
∗ Help lists related functions at the bottom and links
to the documentation.
• To get a version of help with examples and easy-to read
description
– >> doc sin
• To search for a function by specifying keywords:
– >> docsearch sin trigonometric

1.2 Scalar Variables


A variable is a name made of letter or a combination of several
letters (and digits) that is assigned a numerical value.
• Variables can be used in mathematical expressions, in func-
tions, and in any MATLAB statements and commands
A variable is actually a name of a memory allocation.
10
Function Description Example
round(x) Round to the nearest integer. >> round(17/5)
ans =
3
fix(x) Round toward zero. >> fix(13/5)
ans =
2
ceil(x) Round toward infinity. >> ceil(11/5)
ans =
3
floor(x) Round toward minus infinity. >> floor(-9/4)
ans =
-3
rem(x,y) Returns the remainder after x is divided by y. >> rem(13,5)
ans =
3
sign(x) Signum function. Returns 1 if x > 0, -1 if x < 0, and 0 id x = 0. >> sign(5)
ans =
1

Table 1.3: Rounding Functions

• When a new variable is defined, MATLAB allocates an


appropriate memory space where the variable’s assignment
is stored.
• When the variable is used, the stored data is used.
If the variable is assigned new value, the content of the memory
location is replaced.

1.2.1 The Assignment Operator


In MATLAB the = sign is called the assignment operator.
The assignment operator assigns a value to a variable.
Variable name = A numerical value, or a computable expression

• The left-hand side of the assignment operator can include


only one variable name.
• The right-hand side can be a number, or a computable
expression that can include numbers and/or variables that
were previously assigned numerical values.
11
• When Enter key is pressed, the numerical value of the
right-hand side is assigned to the variable, and MATLAB
displays the variable and its assigned value in the next two
lines.
– >> x = 15 [15 is assigned to the variable x].
x =
15
– >> x = 3*x-12
x =
33
The last statement (x = 3x − 12) illustrates the difference
between the assignment operator and the equal sign. If
in this statement the = sign meant equal. the value of x
would be 6 (solving the equation for x).
• If a semicolon is typed at the end of the command, then
when Enter key is pressed, MATLAB does not display
the variable with its assigned value.
• If a variable already exists, typing the variable’s name and
pressing Enter key will display the variable and its value
in the next two lines.
• Several assignments can be typed in the same line, sep-
arated with comma (spaces can can be added after the
comma). When Enter is pressed, the assignments are
executed from left to right and the variables and their as-
signments are displayed.
• A variable that already exists can be assigned a new value.

>> x = 50;
>> x = 42;
>> x
x =
9
>>

• Once a variable is defined it can be used as an argument


in functions.

12
>> x = 0.75;
>> E = sin(x)^2+cos(x)^2
E =
1
>>

1.2.2 Rules About Variables Names


A variable can be named according to the following rules:
• Must begin with a letter.
• Can be up to 63 characters long.
• Can contain letters, digits and underscore character.
• Cannot contain punctuation characters, e.g., period, com-
ma, semicolon.
• MATLAB is case-sensitive: it distinguishes between upper-
case and lowercase letters. For example, AA,Aa,aA and aa
are the names of four different variables.
• No spaces are allowed between characters. Use underscore
where a space is desired.
• Avoid using the name of a built-in function for a variable,
i.e., cos,sin,exp,sqrt, etc. Once a function name is
used to for a variable, the function cannot be used.

1.2.3 Predefined Variables and Keywords


There are 20 keywords reserved by MATLAB for various pur-
poses and cannot be used as variable names. These words are
break, case, classdef, continue, else, elseif, end,
for, function, global, if, otherwise, parfor,
persistent, return, spmd, switch, try, while

• When typed, these words appear in blue. An error message


is displayed if the user tried to use a keyword as a variable
name.
• The keyword can be displayed by typing the command
iskeyword
13
1.2.4 Frequently Used Variables
Some of the predefined variables are:
• ans: A variable that has the value of the last expression
that was not assigned to a specific. If the user does not
assign the value of an expression to a variable, MATLAB
automatically stores the result in ans.
• pi: The number π.
• eps: The smallest difference between two number.
• inf: Used for infinity.

• i: Defined as −, which is 0 : 1.000i.
• j: Same as i
• NaN: Stands for Not-a-Number. Used when MATLAB can-
not determine a valid numeric value, e.g., 0/0.
The variables pi,eps,inf are usually not redefined since they
are frequently used in many applications. Predefined variable
such as i,j are sometime redefined (in loops) when complex
numbers are not involved in the application.

1.2.5 Managing Variables

Command Outcome
clear Removes all variables from the memory
clear x y z Removes only variables x, y and z from the memory.
who Displays a list of the variables currently in the memory
whos Displays a list of the variables currently in the memory
and their sizes together with information about their
bytes and class

1.3 Script Files


Although using Command Window, we can execute a series of
commands, it is not convenient especially for long programs.
The command in the CW cannot be saved and executed again.
14
In addition, the CW is not interactive. This means that only
last command is executed every time Enter key is pressed,
and everything executed before is unchanged.
A better way of executing commands with MATLAB is first to
create a file with a list of commands (program), save it, and
then run (execute) the file.

1.3.1 Notes About Script Files


• A script file is a sequence of MATLAB commands, also
called program.
• When a script file runs, MATLAB executes the commands
in the order they are written, just as if they were typed in
the Command Window.
• When a script file has a command that generates an out-
put, the output is displayed in the Command Window.
• Using a script file is convenient because it can be edited
(corrected, or other changed) and executed many times.
• Script files can be typed and edited in any text editor and
then pasted into the MATLAB editor.
• Script files are also calledM-files because the extension.m
is used when they are saved.

1.3.2 Creating and Saving a Script File


• In MATLAB, script files are created and edited in the Ed-
itor Window.
• From the Command Window, click on the New Script
in the Toolstrip, or click New in the Toolstrip and then
select Script from the menu that open.
• The Editor Window has a Toolstrip at the top and three
tabs Editor, Publish, View above it.
• Before a script file can be executed it has to be saved.
• When saved, MATLAB adds the extension .m to the name.
• The rules for naming a script file follow the rules of naming
a variable.
15
16
• The names of user-defined variables, predefined variables,
and MATLAB commands or functions should not b used
as names of script files.

1.4 Application of MATLAB


Example 1 A trigonometric identity is given by
x tan x + sin x
cos2 = (1.1)
2 2 tan x
Verify that the identity is correct by calculating each side
of the equation, substituting x = x5
Solution
17
>> x = pi/5; % Define x
>> LHS = cos(x/2)^2 % Calculate the left-hand side.
LHS =
0.9045
>> RHS = (tan(x)+sin(x))/(2*tan(x)) % Calculate the right-hand side
RHS =
0.9045

Example 2 An object with an initial temperature of T0


that is placed at time t = 0 inside a chamber that has a
constant temperature of Ts will experience a temperature
change according to the equation
T = Ts + (T0 − Ts )e−kt (1.2)
where T is the temperature of the object at time t, and
k is a constant. A soda can at temperature of 120F is
placed insidea refrigerator where the temperature is 38 F.
Determine, to the nearest degree, the temperature of the
can after three hours. Assume k = 0.45. First, define all
of the variables and then calculate the temperature using
one MATLAB command.
Solution
>>Ts = 38; T0 = 120; k = 0.45; t = 3; % Define variables
>>T = round(Ts+(T0-Ts)*exp(-k*t))
T =
59

Example 3 The balance B of a savings account after t


years when a principal P is invested at an annual interest
rate r and the interest is compound n times a year is given
by  r nt
B =P 1+ (1.3)
n
If the interest is compounded yearly, the balance is given
by
B = P (1 − r)t (1.4)
Suppose $ 5,000 is invested for 17 years in one account
for which the interest is compounded yearly. In addition, $
5,000 is invested in a second account in which the interest
18
is compounded monthly. In both accounts, the interest rate
is 8.5%. Use MATLAB to determine how long (in years
and months) it would take for the balance in the second
account to be the same as the balance of the first account
after 17 years.
Solution We follow these steps:
(a) Calculate B for $ 5,000 invested in a yearly compounded
interest account after 17 years using equation 2.
(b) Calculate t for the B calculate in part (a), from monthly
compounded interest formula, equation 1.
(c) Determine the number of years and months that corre-
spond to t.

%Solution of the Problem


P=5000; r=0.085; ta=17; n=12; % Define variable
B=P*(1+r)^ta
t=log(B/P)/(n*(log(1+r/n))
years=fix(t)
months = ceil((t-year)*12)

When the script file is executed, the following is displayed in


the Command Window:
>> format short g
B =
20011

t =
16.374

years =
16
months =
5

19
CREATING ARRAYS AND MATRICES

2.1 Arrays
• The array is a fundamental data element that MATLAB
uses to store and manipulate data.
• An array is a list of numbers arranged in rows and/or
columns.
• The simplest array(owo-dimensional) is a row or column of
numbers.
• A more complex array is a collection of numbers arranged
in rows and columns.
• Arrays are used to store information and data, as in a table.
• In science and engineering,one dimensional arrays frequent-
ly represent vectors, and two dimensional arrays often rep-
resent matrices.

2.1.1 Creating Vectors


• A one-dimensional array is a list of arranged in a row or
column.
• In MATLAB a vector is created by assigning the elements
of the vector to a variable.
• There are several ways of creating arrays depending on the
source of information that is used for the elements of the
vector.
• When a vector contains specific numbers that are known,
the value of each element is entered directly.
• Each element can also be a mathematical expression that
can include predefined variables, numbers, and functions.
• The elements of row vector are a series of numbers with
constant spacing.
• In such case, the vector is created with MATLAB com-
mands.
20
• A vector can also be created as the result of mathematical
operations.

2.1.2 Array from a Known list of numbers


The vector is created by typing the elements inside square
brackets [ ].

variable_name = [type vector elements]

• Row Vector: To create a row vector, type the elements


with a space or a comma between the elements inside the
square brackets.
• Column Vector: To create a column vector, type the
elements in the square brackets, separated by semicolon
between the elements. Or by typing the left square bracket
[ and then enter the elements then press Enter key after
each element.

>> yr = [1990 1991 1992 1993 1994 1995]


yr =
1990 1991 1992 1993 1994 1995
>> yr = [1990, 1991, 1992, 1993, 1994, 1995]
1990 1991 1992 1993 1994 1995
>> pop=[127; 130; 136;145; 158; 178; 211]
pop =
127
130
136
145
158
178
211
>> pntAV=[2
4
5]
pntAV =
2
4
5

21
2.1.3 The Colon Operator: Creating Vectors with Constant
Spacing

In MATLAB we can create a vector with constant spacing, by


spacing the first term, the spacing, and the last term. In a vec-
tor with constant spacing, the difference between the elements
is the same.
A vector in which the first term is m, the spacing is q, and the
last term is n is created by typing;
variable_name = [m:q:n] or variable_name = m:q:n

>> x = [1:2:13]
x =
1 3 5 7 9 11 13
>> y = 1.5:0.1:2.1
y =
1.5000 1.6000 1.7000 1.8000 1.9000 2.000 2.1000
>> z = [-3:7]
z =
-3 -2 -1 0 1 2 3 4 5 6 7
>> x1 = 21:-3:6
x1 =
21 18 15 12 9 6
>>x1 = 1:10
x1 =
1 2 3 4 5 6 7 8 9 10
>>x2 = 10:-1:1
x2 =
10 9 8 7 6 5 4 3 2 1

• If the numbers m,q,n are such that the value of n cannot


be obtained by adding q’s to m, then the last element in
the vector will be the last number that does not exceed n,
for positive n.
• If only two numbers are typed, then the default for the
spacing is 1.
• Observe that vector x2 has a negative spacing, and the
elements are in descending order.
22
2.1.4 The linspace function: Creating Vector with Equal
(Linear) Spacing
A vector in which the first element is xi, the last element is xf ,
and the number of elements is n is created by typing linspace
command. MATLAB determines the correct spacing In the
variable_name = linspace(xi,xf,n)

>> va = linspace(0,8,6)
va =
0 1.6000 3.2000 4.8000 6.4000 8.0000
>> vb = linspace(30,10,11)
vb =
30 28 26 24 22 20 18 16 14 12 10
>> u = linspace(49.5,0.5)
u =
Columns 1 through 10
49.5000 49.0051 48.5101 48.0152 47.5202 47.0253
46.5303 46.0354 45.5404 45.0455
................
Columns 91 through 100
4.9545 4.4596 3.9646 3.4697 2.9747 2.4798
1.9848 1.4899 0.9949 0.5000
>>

examples above, in creating vector u, we omit the number of


elements n. When a vector is defined in this way using linspace
function, the default number of elements is 100.
Vector variables can also be created using existing variables,
e.g.,
>> x1 = 1:2:9
x1 =
1 3 5 7 9
>> x2 = linspace(3,15,5)
x2 =
3 6 9 12 15
>> newvec = [x1 x2]
newvec =
1 3 5 7 9 3 6 9 12 15

In a special way, function logspace can be used to generate


logarithmically spaced data. It is a logarithmic equivalent of
linspace. For example, the following command generates the
23
set of 10 numbers between 100 and 102 (inclusive):
>>y = logspace(0,2,10)
y =
1.0000 1.6681 2.7826 4.6416 7.7426 12.9155
21.5443 59.9484 100.0000

2.1.5 Random Numbers

In absence of data of use to test a program in MATLAB, it is


useful to test the program first by initializing the data variables
to random numbers.
There are several built-in functions in MATLAB that generate
random numbers.
Function Description Example
rand generate random real number in the range from 0 to 1. >> rand
There are no arguments passed to the rand function. ans =
0.9501
>>rand
ans =
0.2311
rand(1,N) generates a row vectors of N random numbers in rand(1,4)
the range of 0 to 1 ans =
0.2311 0.1034 0.7230
randint(1,1,N) generates a random integer number in the range >>randint(1,1,10)
of 0 to N − 1 ans =
6

2.1.6 Transposing Vectors

Any row vector can be changed into a column vector, and vice
versa. Thus, to generate column vectors, we need to transpose
the row vectors, that is, we need to interchange their rows and
columns.
In MATLAB, this is done using
1. a single quote, or apostrophe (’)
2. transpose command Using transpose command, we have
the following example.
24
>>y = [1 4 8 0 -1]’
y =
1
4
8
0
-1

>>y1 = 0:0.5:2
y1 =
0 0.5000 1.0000 1.5000 2.0000
>>x = transpose(y1)
x =
0
0.5000
1.0000
1.5000
2.0000

2.1.7 Index or Subscripts


We can access and refer to a particular elements in a vector by
means of subscripts. This is done by the name of the vector
variable and the element number (or index or subscript ) in
parenthesis
• A subscript is indicated by parentheses.
• A subscript may be a scalar or a vector.
• In MATLAB, subscript always start at 1.
• Fractional subscripts are not allowed.

>>x = 0:2:30
x =
0 2 4 6 8 10 12 14 16 18 20 22 24 26 30

• >>x(3) Displays the third element of x. The numeral 3 is


the subscript, and the element is 4.
ans =
4

• >>x(2:7) This should give you the second through sev-


enth elements
25
ans =
2 4 6 8 10 12

• >>x(1:2:8) Displays the first, third, fifth, and seventh


elements.
ans =
0 4 8 12

• >>x([1 7 2 6 9 13]) Displays first, seventh, second,


sixth, ninth, and thirteenth elements.
ans =
0 12 2 10 16 24

• >>x([1 7 2 15]) = [ ] Use empty vector to remove el-


ements from a vector. This command will remove elements
1, 7, 2, and 15.
ans =
4 6 8 10 14 16 18 20 22 24 26 28

Changing Value of an Element in a Vector

Thee value stored in a vector can be changed by specifying the


index of subscript. For example to change the fifth element
from the vector z below to now hold the value 15 instead of 16:

>>z = x([1 7 2 6 9 13])


z =
0 12 2 10 16 24
>>z(5) = 15
z =
0 12 2 10 15 24

Extending a Vector

We can add to the number of elements of a vector. If there is


a gap between the end of the vector and the specified element,
0’s are filled in.
26
>>a = [3 55 -7]
a =
3 55 -7
a(4) = 10
a =
3 55 -2 10
>>a(7) = -3
a =
3 55 -7 10 0 0 -3

2.2 Creating Matrix Variables


A matrix may be thought as a table consisting of rows and
columns. Creating matrix variable is just generalization of cre-
ating row and column vectors. That is, the values within a row
are separated by either spaces or commas, and the different
rows are separated by semicolons. For example There must
>>A = [1 2 3; 4 5 6; -3 -6 -9]
A =
1 2 3
4 5 6
-3 -6 -9

be the same number of values in each row. If you attempt to


create a matrix in which there are different numbers of values
in the rows, the result will be an error message.e.g.,

>>A = [1 2 3; 2 4]
Error using vertcat
Dimensions of matrices being concatenated are not consistent.

Different rows in matrix can also be specified by press Enter


key after each row instead of typing a semicolon

27
>>B = [2 6 88
33 5 2]
B =
2 6 88
33 5 2

2.2.1 Creating Matrix using Colon operator


A matrix variable can also be created using iterators where val-
ues on the rows are defined using colon operator. For example

>>B = [2:5; 4:7]


B =
2 3 4 5
4 5 6 7

2.2.2 Creating Matrices of Random numbers


Can be created using rand and randint functions. The first
two arguments to the randint function specify the size of the
matrix of random integer. For example, the following will cre-
ate a 2 × 4 matrix of random integers, in the range from 10 to
40
>>Y = randint(2,4,[10,40])
Y =
35 13 29 18
38 38 13 26

Take Note: In the latest version of MATLAB, randint


function has been replaced by randi function whose arguments
are defined as

• randi(N,m,n) generates an m × n matrix of random in-


tegers in the range from 1 to N.
• randi([N_1,N_2,m,n) generates an m×n matrix of ran-
dome integers in the range from N1 to N2
For the rand function, if single value n is passed to it, n × n
matrix will be created, or passing two arguments will specify
the number of rows and columns

28
>> rand(2)
ans =
0.8909 0.5472
0.9593 0.1386
>>rand(2,3)
ans =
0.1493 0.8407 0.8143
0.2575 0.2543 0.2435

MATLAB has several functions that create special matrices.


These are
• the zeros function: creates a matrix of all zeros. Either
one argument can be passed or two arguments (just like
rand function).
• the ones function: creates a matrix of all ones. It accepts
either one argument or two arguments.
• the eye functions: creates a an identity matrix (a ma-
trix with all diagonal entries being 1s and non-diagonal
elements being 0s). It accepts one argument or two argu-
ments.
• the magic function: Creates a square matrix, and accepts
one argument to be passed. Try it yourself!

2.2.3 Matrix Transpose

A matrix can be transposed, just like any vector using the same
transpose command.
>>A = [1 2 3; 4 5 6]
A =
1 2 3
4 5 6
>>A’
ans =
1 4
2 5
3 6

29
2.2.4 Reffering to and Modifying Matrix Elements
To refer to matrix elements, the row and then the column in-
dices (subscripts) are given in parentheses; always the row in-
dex first and then column index. To refer to an element in ith
row and jth column in a matrix A, we write A(i,j)
>>A = [2:5; 6:9; 0:3; -4:-1]
A =
2 3 4 5
6 7 8 9
0 1 2 3
-4 -3 -2 -1
>>A(2,3)
ans =
8

We can also refer to a subset of a matrix. Using a colon


A(2:3,2:3)
ans =
7 8
1 2

for the row index means all rows, regardless of how many, and
using a colon for the column index means all columns.
>>A(:,3) % This refers to the entire column
ans =
3
7
1
-3
>>A(4,:) % This refers to the entire row
-4 -3 -2 -1

30
COMMAND DESCRIPTION
a( : ) Refers to all the elements of the vector a (either a row or a column).
a(m:n) Refers to elements m through n of the vector a.
A(:,n) Refers to the elements in all the rows of column n of the matrix A.
A(m,:) Refers to the elements in all the columns of row m of the matrix A.
A(:,p:q) Refers to the elements in all the rows between columns p and q of the matrix A.
A(m:n,:) Refers to the elements in all the columns between rows m and n of the matrix A.
A(m:n,p:q) Refers to the elements in rows m through n, and columns p through q.

If a single index is used, MATLAB unwinds the matrix col-


umn by column, starting with the first column. This called
linear indexing. It is a better style when working with ma-
trices to refer to the row and column indices.
An individual element in a matrix can be modified by assign-
>>B = randi([0,100],2,2)
B =
97 52
55 23
>>B(1)
ans =
97
>>B(2)
ans =
55
>>B(3)
ans =
52
>>B(4)
ans =
23

ing a value. An entire row or column could also be changed.


Since the entire row or column is being modified, a vector with
the correct length must be assigned.
Unlike extending a vector, in a matrix, an entire row or
column could be added to extend a matrix. If there is a gap
between the current matrix and the row or column being added,
MATLAB fills in with zeros.

2.2.5 Functions on Matrices


For an m × n matrix A,
31
>>A = [2:4; 3:5];
A(1,2) = 12
A =
2 12 4
3 4 5
>>A(2,:) = 5:7
A =
2 12 4
5 6 7

Function Description
length Returns the number of elements in a vector
size(A) Returns the number of rows and columns in a matrix
numel(A) Returns the total number of elements in any array (vector or matrix)
end Refers to the last element in a vector
reshape(A,m,n) Rearrange a matrix A that has r rows and s columns to have m rows
and n columns. r times s must be equal to m times n.
fliplr(A) Flips matrix from left to right
flipud(A) Flips the matrix up to down
rot90(A) Rotates the matrix counterclockwise 90 degrees.
tril Extracts the lower triangular part of a matrix.
triu Extracts the upper triangular part of a matrix.
diag(A) Creates a vector from the diagonal elements of matrix A.
diag(a) Creates a square matrix with the elements of a in the diagonal.
repmat(A) creates a matrix which consists of an m × n matrix of copies of any matrix.
The command repmat(A,m,n)
abs(A) get an absolute value of every element in the matrix.

32
2.2.6 Element-wise Operation on Matrices
MATLAB has four additional arithmetic operators that work
on corresponding elements of arrays with equal dimensions.
They are called element-wise operations because they are per-
formed element by element.
.* Element-wise Multiplication
./ Element-wise Right division
.\ Element-wise Left division
.^ Element-wise Power (or Exponentiation)

Example 4 The coefficient of friction, µ, can be deter-


mined in an experiment by measuring the force F required
to move a mass m. When F is measured and m is known,
the coefficient of friction can be calculated by
F
µ=
mg
where g = 9.81m/s2.
Results from measuring F in six tests are given in the ta-
ble below. Determine the coefficient in each test, and the
average from all test.
Test # 1 2 3 4 5 6
Mass m(kg) 2 4 5 10 20 50
Force F (N) 12.5 23.5 30 61 117 294

Solution: A solution using script file We save this script file


m = [2 4 5 10 20 50];
F = [12.5 23.5 30 61 117 294];
g = 9.81; mu = F./(m*g)
mu_average = mean(mu)

as friction.m, and call it in the Command Window.


Example 5 A train and a car are approaching a road cross-
ing. At t = 0 the train is 400ft south of the crossing travel-
ing north at a constant speed of 54mph. At the same time,
the car is 200ft west of the crossing traveling east at a speed
33
>>friction
mu =
0.6371 0.5989 0.6116 0.6218 0.5963 0.5994
mu_average =
0.6109

of 28mph and accelerating at 4f t/s2 . Determine the posi-


tion of the train and the car, the distance between them,
and the speed of the traint relative o the car every second
for the next 10 seconds.
To show the results, create an 11 × 6 matrix in which each
row has the time in the first column and the train position,
car position, distance between the train and the car, car
speed, and the speed of the train relative to the car, in the
next five columns, respectively.
Solution
The position of an object that moves along a straight line at a
constant acceleration is given by
1
s = s0 + v0t + at2
2
where s0 and v0 are position and velocity at t0, and a is the
acceleration. Applying this equation to the train and the car
gives:
y = −400 + votrain t (train)
,
1
x = −200 + v0car t + acar t2 (car)
2

34
Introduction to MATLAB Programming

Having used MATLAB interactively in the Command Window


for simple calculations, we now look at cases where many steps
are required before a final result can be obtained. In these cases,
we group the statements together in what is called computer
program.

3.1 Algorithms
An algorithm is a sequence of steps needed to solve a problem.
A problem is broken down into separate steps, and then each
step is further refined until the resulting steps are small enough
to be manageable tasks.
For illustration, consider a problem of calculating the area
of a circle.
• What information is needed in order to solve the problem:
radius of the circle.
Given the radius of the circle, the area of the circle would be
calculated. Once the area has been calculated, it has to be
displayed in some way.
So, the basic algorithm is:
• Get the input: the radius
• Calculate the result: the area
• Display the output.
Where does the input come from?: external file or prompting
the user to type in the value. What is formula needed to area of
the circle?: the area of circle is πr2. The value of π is needed,
which is an example of a constant. Where does the output go?:
to an external file, or to a window on the screen.
For most programs, the basic algorithm consists of three
steps. These are
1. Get the input(s).
2. Calculate the result(s).
3. Display the result(s).
35
3.2 MATLAB Scripts
Once the problem has been analyzed, and an algorithm has
been written, the algorithm is then translated into a particular
program language.
MATLAB uses what we call script files or M-files (because the
extension on filename is .m).
These script files are interpreted, rather than compiled.
A script is a sequence of MATLAB commands that is stored
in a file and saved.
The content of a script can be displayed in the Command Win-
dow using type command.
The script can be executed or run by simply entering the name
of the file (without the .m extension).
We now create a script called circArea.m that calculates the
area of a circle. It assigns a value for the radius, and then
calculates the area based on the radius.
%% circArea.m
1 radius = 5
2
3 area = pi*(radius^2)

To run or execute the script. the name of the file is entered


at the prompt (without .m). When executed, the results of
the two assignment statements are displayed, since the output
was not suppressed for either statement Let us say, we want to
>> circArea
radius =
5
area =
78.5398

modify (if there are errors). To edit an existing file, we


• click File, then Open, then click the name of the file.
• click the Current Directory tab, then double-click the name
of the file.

36

You might also like