P04700 MATLAB Handout - 1 2015
P04700 MATLAB Handout - 1 2015
WHAT IS MATLAB?
MATLAB is an interactive system whose basic data element is an array that does not
require dimensioning. This allows you to solve many technical computing problems,
especially those with matrix and vector formulations, in a fraction of the time it would
take to write a program in a scalar non-interactive language such as C or Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was originally written to
provide easy access to matrix software developed by the LINPACK and EISPACK
projects. Today, MATLAB engines incorporate the LAPACK and BLAS libraries,
embedding the state of the art in software for matrix computation.
MATLAB has evolved over a period of years with input from many users. In
university environments, 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.
The best way to learn MATLAB is by trying yourself. This course will give you a
quick feel for the way MATLAB operates and an appreciation of its power and
flexibility.
To end your MATLAB session, select File -> Exit MATLAB in the desktop, or type
quit in the Command Window.
Window Purpose
Command Window Main window, enters variables, runs programs.
Figure window Contains output from graphic commands.
Editor Window Creates and debugs script and function files.
Help Window Provides help information.
Launch Pad Window Provides access to tools, demos, and documentation.
Command History Window Logs commands entered in the Command Window.
Workspace Window Provides information about the variables that are used.
Current Directory Window Shows the files in the current directory.
• Typing the name of a variable will cause MATLAB to display its current value
• A semicolon at the end of a command suppresses the screen output
• MATLAB uses both parentheses, (), and square brackets, [], and theses are not
interchangeable
• The up and down arrow keys can be used to scroll through your previous
commands. Also, an old command can be recalled by typing the first few
characters followed by up arrow
• You can type help topic to access online help on the command, function
or symbol topic
• The clc command clears the Command Window
• You can quit MATLAB by typing exit or quit
MATLAB is an interactive system. You type commands at the prompt (>>) in the
Command Window and computations are performed when you press enter or return
key.
Precedence Operation
1 (highest) Parentheses. For nested parentheses, the innermost have are executed
first.
2 Exponentiation
3 Multiplication, division (equal precedence).
4 (lowest) Addition, subtraction.
Example 1 Calculate:
( 4 250 + 23)2
(a) 43 ⋅
e(45−3 )
3
π
tan ln 8
π π
2
5 7 6 ,
(b) cos 2 sin + 5
6 8 7⋅
2
DISPLAY FORMATS
MATLAB displays floating point numbers to 4 decimal digits, by default, but always
stores numbers and computes to the equivalent of 16 decimal digits. The output
format can be changed using the format command:
>>10*exp(1)
>>format long
>>10*exp(1)
Variable names:
• Can be up to 63 characters long.
• Can contain letters, digits, and the underscore character.
• Must begin with a letter.
• Upper and lower case characters are not equivalent (MATLAB is case
sensitive)
• Avoid using names of a built-in function for a variable (i.e. avoid using: cos,
sin, exp, sqrt, etc.). Once a function name is used to define a variable,
the function cannot be used.
>>x=sin(22)
>>y=2*x+exp(-3)/(1+cos(.1));
>>y
>>x=2,y=cos(.3),z=3*x*y
>>x=5;y=cos(.5);z=x*y^2
T = Ts + (T0 − Ts ) e − kt ,
A soda can at a temperature of 48 C (was left in the car) is placed inside a
refrigerator where the temperature is 2 C . Determine, to the nearest degree, the
temperature of the can after three hours. Assume k = 0.45 . First define all the
variables and then calculate the temperature using one MATLAB command.
Predefined Variables
ans If the user does not assign the value of an expression to a variable, MATLAB
automatically stores the result in ans.
pi π
eps The smallest difference between two numbers: 2 −52 = 2.2204e − 016
inf ∞
i −1
j −1
NaN Stands for Not-a-Number. Used when Matlab cannot determine a valid
numerical value.
>>2-3*j,2-3j,2-3*sqrt(-1),complex(2,-3)
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 variables currently in the memory
whos Displays a list of variables currently in the memory and their
size together with information about their bytes and class
PROBLEMS
37 log10 (76) 3
1. Calculate + 910 .
73 + 546
a) x3 + 5 x 2 − 26.7 x − 52
14 x3
b)
e3 x
c) ln x 2 − x3
4. Flowers are packed in boxes such that a dozen are placed in each box.
Determine how many boxes are needed to pack 751 flowers, using the ceil
function.
2 E
M = ln ,
3 E0
>>a=[1 5 7 11]
>>length(a)
>>a’
>>b=[2;31;47;103]
The colon notation is useful for generating vectors of equally spaced values.
>>v=1:4
>>w=2:3:10,y=1:-0.25:0
>>vb=linspace(30,10,11)
>>u=linspace(49.5,0.5)
Vector addresing
>>va(4)
>>u(20:44)
>>vb([2,7,10])
>>vb([2,7:10])
>>u(5)^u(8)+sqrt(vb(7))
>>va(10)=4
>>vc(5)=24
>>v(6)=[]
>>v(2:4)=[]
>>vb([2,7,10])=[]
Conventions:
a) square brackets enclose an array,
b) spaces or commas separate entries in a
row,
c) semicolons separate rows.
>>size(A)
>>B=[7 2 76 33 8
1 98 6 25 6
5 54 68 9 0]
>>C=[1:2:11;0:5:25;linspace(10,60,6);67 2 43 68 4 13]
>>D=C’
Matrix addresing
>>C(2,3)
>>C(1,:)
>>C(:,2)
>>C(2:4,:)
>>C([2,4],:)
>>C(:,1:3)
>>C(:,[1,3])
>>C(2:4,1:3)
>>C(:)
>>I3=eye(3,3),Y=zeros(3,5),Z=ones(2)
>>F=rand(6),G=randn(1,5)
>>inv(F)
>>ans*F
>>F(2,:)=[]
>>F(:,2:4)=[]
>>E=[1 2 3 4; 5 6 7 8]
>>E(3,:)=[10:4:22]
>>EI=[E I3]
>>M=[3 6 9; 8 5 11]
>>MI=[M;I3]
>>M(4,5)=17
>>N(3,4)=15
Arithmetic operators on matrices and vectors come in two distinct forms. Matrix sense
operations are based on the normal rules of linear algebra and are obtained with the
usual symbols +,-,*,/ and ^. Array sense operations are defined to act element-by-
element and are generally obtained by preceding the symbol with a dot.
Addition and subtraction can be used with arrays of identical size (the same number
of rows and columns).
>>clear all
>>a=[1 2 3]
>>b=[4;5;6]
>>a+b
>>a+b’
>>A=[5 -3 8; 9 2 10]
>>B=[10 7 4;-11 15 1]
>>C=A-B
A ∗ B = C
m×n n× p m× p
1 4 3 5 4 (1 ⋅ 5 + 4 ⋅1 + 3 ⋅ 2 ) (1⋅ 4 + 4 ⋅ 3 + 3 ⋅ 6 ) 15 34
2 6 1 1 3 = 2 ⋅ 5 + 6 ⋅1 + 1 ⋅ 2
( ) ( 2 ⋅ 4 + 6 ⋅ 3 + 1⋅ 6 ) = 1832
5 2 8 2 6 ( 5 ⋅ 5 + 2 ⋅1 + 8 ⋅ 2 ) ( 5 ⋅ 4 + 2 ⋅ 3 + 8 ⋅ 6 ) 43 74
3×3 3×2 3×2
>>clear A B C
>>A=[1 4 3; 2 6 1; 5 2 8]
>>B=[5 4; 1 3; 2 6]
>>C=A*B
>>a*b
>>D=b*a
>>a*a
>>a*a'
>>c=a^2
>>A^5
>>A^(-3)
A X = B,
n×n n×1 n×1
Or equivalently, X T AT = BT .
1. A X = B
n×n n×1 n×1
2. X C = D
1×n n×n 1×n
4x − 2 y + 6z = 8
2x + 8 y + 2z = 4 .
6 x + 10 y + 3z = 0
Array sense operations can only be done with arrays of the same size.
a./ b = [ a1 / b1 a2 / b2 a3 / b3 a4 / b4 ] ,
a. \ b = [b1 / a1 b2 / a2 b3 / a3 b4 / a4 ]
a. ^ b = ( a1 ) 1 ( a2 ) ( a3 ) ( a4 ) ,
b b2 b3 b4
a. ^ n = ( a1 ) ( a2 ) ( a3 ) ( a4 ) .
n n n n
a b a12b12 a13b13
A.* B = 11 11 ,
a21b21 a22b22 a23b23
b / a b /a b13 / a13
A. \ B = 11 11 12 12 ,
b21 / a21 b22 / a22 b23 / a23
A. ^ n = .
( a21 ) ( a22 ) ( a23 )
n n n
1 2 1 1
Example 2 Given X = , Y = and p = 2 compute: X − Y , X + Y ,
3 4 1 1
X + p , p − Y , X * Y , X .* Y , X \ Y , Y ./ X , p * X , p.* X , X / p , p./ X , X . \ p ,
p. \ X , X . ^ X , X ^ p , X . ^ p , p. ^ X .
>>y=cos(x)
>>det(A)
>>inv(A)
>>E=sqrt(A)
>>a=[5 9 2 4 11 6 7 11 0 1]
>>mean(a)
>>c=max(a)
>>[d,n]=max(a)
>>sum(a)
>>sort(a)
>>std(a)
Example 3 For testing the production of a new plastic, the following volume and
mass measurements were taken from 8 samples.
Enter the results in two vectors, and then find the densities, in grams per cm3. Find the
sample with the highest density. Find the sample with the smallest density. Arrange
the densities in ascending order. Find the mean and standard deviation.
PROBLEMS
6 43 2 11 87
1. Create the following matrix A = 12 6 34 0 5
34 18 7 41 9
a) Create a five-element row vector named va that contains the elements
of the second row of A.
b) Create a three-element row vector named vb that contains the elements
of the fourth column of A.
c) Create a ten-element row vector named vc that contains the elements
of the first and second rows of A.
d) Create a six-element row vector named vd that contains the elements
of the second and fifth columns of A.
1 2 3 4 5 6 7
2 4 6 8 10 12 14
2. Create the following matrix A =
21 18 15 12 9 6 3
5 10 15 20 25 30 35
Create a 3 × 5 matrix B from the 1st, 3rd and 4th rows, and the 1st,3rd through 5th,
and 7th columns of the matrix A.
3. Using the eye command create the array A shown on the left below. Then
using the colon notation to address the elements in the array, change the array
to be like the one shown on the right.
1 0 0 0 0 0 0 2 2 2 0 5 5 5
0 1 0 0 0 0 0 2 2 2 0 5 5 5
0 0 1 0 0 0 0 3 3 3 0 5 5 5
A = 0 0 0 1 0 0 0 A = 0 0 0 1 0 0 0
0 0 0 0 1 0 0 4 4 7 0 9 9 9
0 0 0 0 0 1 0 4 4 7 0 9 9 9
0 0 0 0 0 0 1 4 4 7 0 9 9 9
4. For the function y = ( x 2 + 1)3 x 3 , calculate the value of y for the following
values of x: -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3. Solve the problem by
first creating a vector x, and then creating a vector y, using element-by-
element calculations.
5. The depth of a well, d , in meters can be determined from the time it takes for
a stone that is dropped into the well (zero initial velocity) to hit the bottom by
1
d = gt 2 , where t is the time in seconds and g = 9.81 m s 2 . Determine d
2
for t = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. (Create a vector t and determine d using
element-by-element calculations.)
y
xy +
z= x + 12 x / y .
( y− x)
( x + y)
7. Solve the following system of four linear equations:
5x + 4y − 2z + 6w = 4
3x + 6y + 6 z + 4.5w = 13.5
.
6 x + 12 y − 2 z + 16 w = 20
4x − 2y + 2z − 4w = 6
M-FILES
Although you can do many useful computations working entirely at the MATLAB
command line, sooner or later you will need to write M-files. These are the equivalent
of programs, functions, subroutines and procedures in other programming languages.
An M-file is a text file that has a .m filename extension and contains MATLAB
commands. There are two types:
Script M-files (command files) have no input or output arguments and operate on
variables in the workspace.
Function M-files contain a function definition line and can accept input arguments
and return output arguments, and their internal variables are local to the function
(unless declared global).
SCRIPT FILES
Global Variables
Global variables are variables that, once created in one part of MATLAB are
recognized in other parts of MATLAB. This is the case for variables in the Command
Window and script files since both operate on variables in the workspace. When a
variable is defined in the Command Window, it is also recognized and can be used in
a script file. In the same way, if a variable is defined in a script file it is also
recognized and can be used in the Command Window. In other words, once the
variable is created it exists, can be used, and can be reassigned a new value in both the
Command Window and a script file.
M-FILES 20
P04700 COMPUTATION AND MODELLING
Example 1 A projectile is fired with a muzzle speed v0 = 750 (m/s). Calculate the
distance d that the projectile will hit the ground if the firing angle θ is changed from
5 to 85 in 5 increments. Use element-by-element calculation. To show results,
create a 17 × 2 matrix in which the elements in the first column are the firing angles
and the elements in the second column are the corresponding distances rounded to the
nearest integers. The gravitational acceleration g = 9.81 m/s 2 .
The motion of a projectile can be analysed by considering the horizontal and vertical
components. The initial velocity v0 can be resolved into horizontal and vertical
components:
v0 x = v0 cos θ , and v0 y = v0 sin θ .
In the vertical direction the velocity and the position of the projectile are given by:
1 2
v y = v0 y − gt and y = v0 y t − gt
2
The time it takes the projectile to reach the highest point ( v y = 0 ) and the
corresponding height are given by:
v0 y v0 y 2
th max = and hmax = .
g 2g
The total flying time is twice the time it takes the projectile to reach the highest point,
t f = 2th max . In the horizontal direction the velocity is constant vx = v0 x , and the
position of the projectile is given by:
x = v0 x t .
M-FILES 21
P04700 COMPUTATION AND MODELLING
Example 2 Modify the script file created for Example 1 to allow the firing angle θ
to be defined and assigned a value in the Command Window.
M-FILES 22
P04700 COMPUTATION AND MODELLING
3. The variable is defined in the script file, but a specific value is entered in the
Command Window when the script file is executed.
In this case the variable is defined in the script file and when the file is executed, the
user is prompted to assign a value to the variable in the Command Window. This is
done by using the input command to create the variable.
Example 3 Three forces are applied to a bracket as shown. Write a script file that
determines the total force applied to the bracket. The magnitudes of the forces are
assigned to the variables by using the input command. Find the total force applied
to the bracket for F1 = 400N , F2 = 500N , and F3 = 700N .
F3
F2
143
30
20 x
F1
( )
F = Fx i + Fy j = F cos θ i + F sin θ j = F cos θ i + sin θ j ,
where F is the magnitude of the force, θ is its angle relative to the x axis, Fx and
Fy are the components of F in the directions of the x axis and y axis, respectively,
and i and j are the unit vectors in these directions. If Fx and Fy are known, then F
and θ can be determined by:
Fx
F = Fx2 + Fy2 and tan θ = .
Fy
The total force applied to the bracket is obtained by adding the forces that are acting
on the bracket.
M-FILES 23
P04700 COMPUTATION AND MODELLING
Output Commands
One command that is frequently used to generate output is the disp. The disp
command is used to display the elements of a variable without displaying the name of
the variable, and to display text.
disp(name of a variable)
disp(‘text as string’)
Example 4 Modify the program written for Example 1 to display a table with the
firing angles listed in the first column and the corresponding distances (m) in the
second column.
The fprintf command can be used to display output (text and data) on the screen
or to save it to a file. With this command (unlike the disp command) the output can
be formatted. With many available options, the fprintf command can be long and
complicated.
M-FILES 24
P04700 COMPUTATION AND MODELLING
PROBLEMS
Solve the following problems by first writing a program in a script file and then
running the file in the Command Window.
1 2
v = at and d= at .
2
Determine v and d as every second for the first 10 seconds for a car with
acceleration of a = 1.55 m/s 2 . Display the results in a three-column table in
which the first column is time (s), the second distance (m), and the third is the
velocity ( m/s ).
Determine x and v for every two hundredth of a second for the first half
second after impact. Display the results in a three-column table in which the
first column is time (s), the second is displacement (m), and the third is
velocity (m/s).
3. A train and a car are approaching a road crossing. At t = 0 the train is 400 ft.
south of the crossing travelling north at a constant speed of 54 mi/h. At the
same time the car is 200 ft. west of the crossing travelling east at a speed of 28
mi/h and accelerating at 4 ft/s 2 . Determine the positions of the train and the
car, the distance between them, and the speed of the train relative to the car
every second for the next 10 seconds. Display the results in a six-column table
in which the first column is time (s), the second train position (ft), the third
car position (ft), the fourth the distance between the train and the car (ft), the
fifth the car speed (ft/s), and the sixth the speed of the train relative to the car
(ft/s).
M-FILES 25
P04700 COMPUTATION AND MODELLING
Functions are created and edited, like script files, in the Editor/Debugger Window.The
first executable line in a function file must be the function definition line. Otherwise
the file is considered a script file. The function definition line:
• Defines the file as a function file.
• Defines the name of the function.
• Defines the number and order of the input and output arguments.
- The word function must be the first word and must be typed in lower-case letters.
- A list of output arguments are typed inside square brackets.
- A Function File is saved with a name that is identical to the function name in the
function definition line. In this way the function is called (used) by using the function
name.
- A list of input arguments are typed inside parentheses.
M-FILES 26
P04700 COMPUTATION AND MODELLING
x 4 3x + 5
Example 5 Write a function file for the function f ( x) = . Write the
( x 2 + 1) 2
function such that x can be a vector. Use the function to calculate:
a) f ( x) for x = 6 .
Example 6 Create a function file that calculates the trajectory of a projectile. The
inputs to the function are the initial velocity and the angle at which the projectile is
fired. The outputs for the function are the maximum height and distance. Use the
function to calculate the trajectory of a projectile that is fired at a velocity of 230m/s
at an angle of 39 .
• Both script files and function files are saved with the extension .m
• The variables in a function file are local. The variables in a script file are
recognized in the Command Window.
• Script files can use variables that have been defined in the workspace
• Function files can accept data through input arguments and can return data
through output arguments
• When a function file is saved, the name of the file should be the same as the
name of the function
M-FILES 27
P04700 COMPUTATION AND MODELLING
Inline Functions
Function files can be used for simple mathematical functions, for large and
complicated math functions that require extensive programming, and as subprograms
in large computer programs.
Inline functions are created with the inline command according to the following
format:
>>FA=inline(‘exp(x^2)/sqrt(x^2+5)’)
>>FA(2)
>>z=FA(3)
If x is expected to be an array, and the function calculated for each element, then the
function must be modified for element-by-element calculations.
>>FA=inline(‘exp(x.^2)./sqrt(x.^2+5)’)
M-FILES 28
P04700 COMPUTATION AND MODELLING
An inline function that has two or more independent variables can be written in the
format shown or by using the following format:
name=inline(‘mathematical expression’,’arg1’,’arg2’,’arg3’)
In the format shown here the order of arguments in the function is defined. If the
previous format is used, MATLAB arranges the arguments in alphabetical order.
>>HA=inline(‘2*x^2-4*x*y+y^2’)
>>HA(2,3)
Example 7 Write an inline function that calculates the distance between two
points in a plane when the position of the points is given in cartesian coordinates. Use
the inline function to calculate the distance between point A(2, −5) and B (−6, −1) .
d= ( x A − xB ) + ( y A − y B )
2 2
.
M-FILES 29
P04700 COMPUTATION AND MODELLING
The feval (function evaluate) command evaluates the value of a function for a
given value (or values) of the function’s argument (or arguments). The format of the
command is:
• If there is more than one input argument, the arguments are separated with
commas.
• If there is more than one output argument, the variables on the left-hand side
of the assignment operator are typed inside brackets and separated with
commas.
>>feval(‘sqrt’,64)
>>x=feval(‘sin’,pi/6)
>>[H,D]=feval(‘trajectory’,150,45)
M-FILES 30
P04700 COMPUTATION AND MODELLING
PROBLEMS
σ yy
τ xy
σ xx
The maximum and the minimum normal stresses (principal stresses) at the
point, σ max and σ min , are calculated from the stress components by:
σ xx + σ yy σ − σ yy
2
σ max = ± xx + τ xy .
2
min 2 2
Use the function to determine the principal stresses for the following states
of stress:
M-FILES 31
P04700 COMPUTATION AND MODELLING
For the function name and arguments use g=fgrade(R). The input
argument R is a matrix in which the elements in each row are the grades
of one student. The first six columns are the homework grades (numbers
between 0 and 10), the next three columns are the midterm grades
(numbers between 0 and 100), and the last column is the final exam grade
(a number between 0 and 100). The output from the function, g, is a
column vector with the final grades for the course. Each row has the
course grade of the student with the grades in the corresponding row of
the matrix R.
The function can be used to calculate the grades of any number of
students. For one student the matrix R has one row. Use the function in
the following cases:
a) Use the Command Window to calculate the grade of one student with the
following grades: 8, 9, 6, 10, 9, 7, 76, 86, 91, 80.
b) Write a program in a script file. The program asks the user to enter the
students’ grades in an array (each student a row). The program then
calculates the final grades by using the function fgrade. Run the script
file in the Command Window to calculate the grades of the following
students:
Student A: 7, 10, 6, 9, 10, 9, 91, 71, 81, 88.
Student B: 5, 5, 6, 1, 8, 6, 59, 72, 66, 59.
Student C: 6, 8, 10, 4, 5, 9, 72, 78, 84, 78.
Student D: 7, 7, 8, 8, 9, 8, 83, 82, 81, 84.
M-FILES 32