0% found this document useful (0 votes)
28 views32 pages

P04700 MATLAB Handout - 1 2015

The document provides information about MATLAB including what it is, its uses, basic functions and commands. MATLAB is an interactive system for technical computing that integrates computation, visualization and programming. It allows matrix and vector problems to be solved more quickly than other languages like C or Fortran.
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)
28 views32 pages

P04700 MATLAB Handout - 1 2015

The document provides information about MATLAB including what it is, its uses, basic functions and commands. MATLAB is an interactive system for technical computing that integrates computation, visualization and programming. It allows matrix and vector problems to be solved more quickly than other languages like C or Fortran.
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/ 32

P04700 COMPUTATION AND MODELLING

STARTING WITH MATLAB

WHAT IS MATLAB?

MATLAB® is a high-performance language for technical computing. It integrates


computation, visualization, and programming in an easy-to-use environment where
problems and solutions are expressed in familiar mathematical notation.

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.

MATLAB features a family of add-on application-specific solutions called toolboxes.


Very important to most users of MATLAB, toolboxes 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. Areas in which toolboxes are available include signal processing, control
systems, neural networks, fuzzy logic, wavelets, simulation, and many others.

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.

STARTING WITH MATLAB 1


P04700 COMPUTATION AND MODELLING

STARTING MATLAB, MATLAB WINDOWS

On Windows platforms, start MATLAB by double-clicking the MATLAB shortcut


icon on your Windows desktop.

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.

Working in the Command Window

Important points to remember:

• 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

STARTING WITH MATLAB 2


P04700 COMPUTATION AND MODELLING

USING MATLAB AS A CALCULATOR

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.

Operation Symbol Example


Addition + 5+3
Subtraction - 5-3
Multiplication * 5*3
Right division / 5/3
Left division \ 5\3=3/5
Exponentiation ^ 5^3

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.

Elementary Mathematical built-in functions

Function Description Example


sqrt(x) x >> sqrt(81)
exp(x) ex >> exp(5)
abs(x) x >> abs(-24)
log(x) ln( x) >> log(1000)
log10(x) log10 ( x) >> log10(1000)
factorial(x) x! >> factorial(5)
sin(x) sin( x) , x in radians >> sin(pi/6)
cos(x) cos( x) , x in radians >> cos(pi/6)
tan(x) tan( x) , x in radians >> tan(pi/6)
cot(x) cot( x) , x in radians >> cot(pi/6)
sind(x) sin( x) , x in degrees >> sin(30)
cosd(x) cos( x) , x in degrees >> cos(30)
tand(x) tan( x) , x in degrees >> tan(30)
cotd(x) cot( x) , x in degrees >> cot(30)
round(x) Round to the nearest integer >> round(17/5)
fix(x) Round towards 0 >> fix(13/5)
ceil(x) Round towards ∞ >> ceil(11/5)
floor(x) Round towards −∞ >> floor(-9/4)
rem(x,y) Returns the remainder of x y >> rem(13,5)

STARTING WITH MATLAB 3


P04700 COMPUTATION AND MODELLING

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

STARTING WITH MATLAB 4


P04700 COMPUTATION AND MODELLING

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)

Command Description Example


format short Scaled fixed point format 27.1828
with 4 decimal digits for
0.001 ≤ number ≤ 1000.
Otherwise display format
short e.
format long Scaled fixed point format, 27.18281828459045
with 14 decimal digits for
0.001 ≤ number ≤ 1000.
Otherwise display format
long e.
format short e Floating point format, with 4 2.7183e+001
decimal digits.
format long e Floating point format, with 15 2.718281828459045e+001
decimal digits.
format short g Best of fixed or floating 27.183
point, with 5 digits.
format long g Best of fixed or floating 27.1828182845905
point, with 15 digits.
format hex Hexadecimal representation 403b2ecd2dd96d44
of a binary double-precision
number.
format bank Fixed dollars and cents. 27.18
format rat Ratio of small integers. 2528/93
format compact Eliminates empty lines to allow more lines with information
displayed on the screen.
format loose Adds empty lines (opposite of compact).

STARTING WITH MATLAB 5


P04700 COMPUTATION AND MODELLING

DEFINING SCALAR VARIABLES

= is called the assignment operator

The assignment operator assigns a value to a variable. A variable is a name made of a


combination of letters and digits that is assigned a numerical value. Once a variable is
assigned a numerical value, it can be used in mathematical expressions, in functions,
and in any MATLAB statements and commands.

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

Example 2 An object with an initial temperature of T0 that is placed at the 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 ,

where T is the temperature of the object at time t , and k is a constant.

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.

STARTING WITH MATLAB 6


P04700 COMPUTATION AND MODELLING

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)

Useful Commands For 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 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

STARTING WITH MATLAB 7


P04700 COMPUTATION AND MODELLING

PROBLEMS

37 log10 (76) 3
1. Calculate + 910 .
73 + 546

2. Define the variable x as x = 13.5 , then evaluate:

a) x3 + 5 x 2 − 26.7 x − 52

14 x3
b)
e3 x

c) ln x 2 − x3

3. Define the variables a = 15.62, b = −7.08, c = 62.5 and d = 0.5(ab − c) .


Evaluate:
ab (a + d ) 2
a) a+ ,
c ab
ad + cd
20 30
d 
 
+
b) de 2  + a b .
(a + b + c + d )

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.

5. The magnitude M of an earthquake on the Richter scale is given by:

2  E 
M = ln   ,
3  E0 

where E is the energy released by the earthquake, and E0 = 104.4 Joules is a


constant (i.e. the energy of a small reference earthquake). Determine how
many times more energy is released from an earthquake that registers 7.2 on
the Richter scale than an earthquake that registers 5.3.

STARTING WITH MATLAB 8


P04700 COMPUTATION AND MODELLING

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH


ARRAYS
The array is the fundamental form that MATLAB uses to store and manipulate data.

CREATING A ONE-DIMENSIONAL ARRAY (VECTOR)

>>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

The linspace command is used to create a vector with constant spacing by


specifying the first and last terms and the number of elements.
>>va=linspace(0,8,6)

>>vb=linspace(30,10,11)

>>u=linspace(49.5,0.5)

Vector addresing

v(k) Refers to the element of the vector v in position k.


v(:) Refers to all the elements of the vector v.
v(m:n) Refers to the elements m through n of the vector v.
v([k,m,n]) Refers to the elements of the vector v in positions k, m, and n.
v([k,m:n]) Refers to the elements of the vector v in position k, and m through n.

>>va(4)

>>u(20:44)

>>vb([2,7,10])

>>vb([2,7:10])

>>u(5)^u(8)+sqrt(vb(7))

Adding elements to a vector


>>v(5:10)=10:5:35

>>va(10)=4

>>vc(5)=24

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 9


P04700 COMPUTATION AND MODELLING

Deleting vector elements

>>v(6)=[]

>>v(2:4)=[]

>>vb([2,7,10])=[]

CREATING A TWO-DIMENSIONAL ARRAY (MATRIX)

Conventions:
a) square brackets enclose an array,
b) spaces or commas separate entries in a
row,
c) semicolons separate rows.

>>A=[5 35 43; 4 76 81;21 32 40]

>>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

A(:,n) Refers to the elements in all the rows of column n of the


matrix A.
A(n,:) Refers to the elements in all the columns of row n of the
matrix A.
A(:,m:n) Refers to the elements in all the rows between columns m and
n 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 of the matrix A.
A(:,[m,n]) Refers to the elements in all the rows of the columns m and n
of the matrix A.
A([m,n],:) Refers to the elements in all the columns of the rows m and n
of the matrix A.
A([m,n],[p,q]) Refers to the elements in rows m and n and columns p and q
of the matrix A.

>>C(2,3)

>>C(1,:)

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 10


P04700 COMPUTATION AND MODELLING

>>C(:,2)

>>C(2:4,:)

>>C([2,4],:)

>>C(:,1:3)

>>C(:,[1,3])

>>C(2:4,1:3)

>>C(:)

You can build certain types of matrices automatically.

>>I3=eye(3,3),Y=zeros(3,5),Z=ones(2)

>>F=rand(6),G=randn(1,5)

>>inv(F)

>>ans*F

The notation [] denotes an empty 0-by-0 matrix. Assigning [] to a row or a column is


one way to delete that row or column from a matrix.

>>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

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 11


P04700 COMPUTATION AND MODELLING

MATHEMATICAL OPERATIONS WITH ARRAYS

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.

Operation Matrix sense Array sense


Addition + +
Subtraction - -
Multiplication * .*
Left division \ .\
Right division / ./
Exponentiation ^ .^

MATLAB notation Mathematical equivalent


Right division: a / b a
b
Left division: a \ b b
a

Matrix Sense Operations

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

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 12


P04700 COMPUTATION AND MODELLING

The multiplication operation * is executed by MATLAB according to the rules of


Linear Algebra. The operation A ∗ B makes sense only if the number of columns in
the matrix A equals the number of rows in the matrix B . The result is a matrix C
that has the same number of rows as A and the same number of columns as 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'

The exponentiation ^ can only be executed with a square matrix:

( n > 0) , A− n = ( A−1 ) =  ( n > 0) .


n
A0 = I , An = 
AA
⋯
A A−1
A−
1 −1
⋯ A
n factors n factors

>>c=a^2

>>A^5

>>A^(-3)

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 13


P04700 COMPUTATION AND MODELLING

Systems of linear equations

Matrix multiplication has an important application to systems of linear equations.


Consider a system of n linear equations in n unknowns:

a11 x1 + a12 x 2 + ... + a1n x n = b1


a 21 x1 + a 22 x 2 + ... + a 2 n x n = b2
.
⋮⋮
a n1 x1 + a n 2 x 2 + ... + a nn x n = bn

This system can be replaced by the single matrix equation

A X = B,
n×n n×1 n×1

 a11 a12 ⋯ a1n   x1   b1 


     
a a22 ⋯ a2 n  x2  b
where A =  21 , X=  , and B =  2  .
 ⋮ ⋮ ⋱ ⋮  ⋮  ⋮
     
 an1 an 2 ⋯ ann   xn   bn 

Or equivalently, X T AT = BT .

Solving matrix equations in MATLAB

1. A X = B
n×n n×1 n×1

The solution X = A−1 B can be computed in MATLAB in two ways:

X=inv(A)*B ( A−1 is calculated first, and then A−1 B is computed),

X=A\B (Solution is obtained numerically using Gaussian elimination).

The left division \ method is recommended for solving the equation AX = B


because the calculation of the inverse may be less accurate than the Gauss
elimination method when large matrices are involved.

2. X C = D
1×n n×n 1×n

The solution X = DC −1 can be computed in MATLAB in two ways:

X=D*inv(C) ( C −1 is calculated first, and then DC −1 is computed),

X=D/C (Using the right division / character).

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 14


P04700 COMPUTATION AND MODELLING

Example 1 Solve the following linear system of equations:

4x − 2 y + 6z = 8
2x + 8 y + 2z = 4 .
6 x + 10 y + 3z = 0

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 15


P04700 COMPUTATION AND MODELLING

Array Sense Operations

Array sense operations can only be done with arrays of the same size.

Let a = [ a1 a2 a3 a4 ] and b = [b1 b2 b3 b4 ] , then

a.* b = [ a1b1 a2b2 a3b3 a4b4 ] ,

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 a12 a13   b11 b12 b13 


Let A =  11  and B =  , then
 a21 a22 a23  b21 b22 b23 

a b a12b12 a13b13 
A.* B =  11 11 ,
 a21b21 a22b22 a23b23 

a / b a12 / b12 a13 / b13 


A./ B =  11 11 ,
 a21 / b21 a22 / b22 a23 / b23 

b / a b /a b13 / a13 
A. \ B =  11 11 12 12 ,
b21 / a21 b22 / a22 b23 / a23 

 ( a11 )b11 ( a12 )


b12
( a13 )
b13

A. ^ B =  ,
( a21 ) 21 ( a22 ) ( a23 )
b b b
22 23


 ( a11 )n ( a12 ) ( a13 ) 


n n

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 .

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 16


P04700 COMPUTATION AND MODELLING

Using Arrays in MATLAB Built-In Mathematical Functions


>>x=[0:pi/6:pi]

>>y=cos(x)

>>A=[1 4 9; 16 25 36; 49 64 81]

>>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.

Volume ( mm3 ) Mass (g)


785 1.79
475 1.09
1260 2.93
1080 2.52
565 1.29
1070 2.39
1550 3.56
985 2.27

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.

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 17


P04700 COMPUTATION AND MODELLING

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.)

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 18


P04700 COMPUTATION AND MODELLING

6. Define x and y as the vectors x = 2, 4, 6, 8, 10 and y = 3, 6, 9, 12, 15 . Then,


use them in the following expression to calculate z 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

CREATING ARRAYS. MATHEMATICAL OPERATIONS WITH ARRAYS 19


P04700 COMPUTATION AND MODELLING

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

• A script file is a sequence of MATLAB commands, also called a 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 the output, the output is
displayed in the Command Window.
• Using a script file is convenient because it can be edited (corrected and/or
changed) and executed many times.
• Script files can be edited in any text editor and then pasted into the MATLAB
editor.
• Script files should have the extension .m when they are saved.
• A script file can be executed by typing its name in the Command Window and
then pressing the Enter key, or directly from the Editor Window by clicking
on the Run icon.

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

Input to a Script File

1. The variable is defined and assigned a value in the script file.

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

2. The variable is defined and assigned a value in the Command Window.

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.

variable_name=input(‘string with a message to be


displayed in the Command Window’)

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

In a Cartesian coordinate system a two-dimensional vector F can be written as:

( )
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

As discussed before MATLAB automatically generates a display when some


commands are executed. For example, when a variable is assigned a value, or the
name of a previously assigned variable is typed and the Enter key is pressed,
MATLAB displays the variable and its value. This type of output is not displayed if a
semicolon is typed at the end of the command. In addition to this automatic display,
MATLAB has several commands that can be used to generate displays. The displays
can be messages that provide information, numerical data, and plots.

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. The velocity, v, and the distance d, as a function of time, of a car that


accelerates from rest at constant acceleration, a, are given by:

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 ).

2. A railroad bumper is designed to v


slow down a rapidly moving railroad x
car. After a 20,000 kg railroad car
travelling at 20 m/s engages the m
bumper, its displacement x (in
meters) and velocity v (in m/s) as a
function of time t (in seconds) is
given by:

x = 4.219 ( e−1.58t − e −6.32 t ) and v = 26.67e −6.32t − 6.67e−1.58t .

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 AND FUNCTION FILES

A simple function in mathematics, f ( x) , associates a unique number to each value of


x. The function can be expressed in the form y = f ( x) , where f ( x) is usually a
mathematical expression in terms of x. A value of y (output) is obtained when a value
of x (input) is substituted in the expression.

Many functions are programmed inside MATLAB as built-in functions: sin(x),


cos(x), sqrt(x), exp(x), …

Frequently, in computer programs, there is a need to calculate the value of functions


that are not built-in. When a function is simple and needs to be calculated only once,
it can be typed as part of a program. However, when a function needs to be evaluated
many times for different values of arguments it is convenient to create a user-defined
function. Once the new function is created (saved) it can be used just like the built-in
functions.

A user-defined function is a MATLAB program that is created by the user, saved as a


function file, and then can be used like a built-in function. The function can be a
simple single mathematical expression or a complicated and involved series of
calculations. The main feature of a function file is that it has an input and an output.
The input and output can be one or several variables, and each can be a scalar, vector
or an array of any size. Schematically, a function file can be illustrated by:

Input data Output


Function
File

Creating a Function File

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 form of the function definition line is:

function [output arguments]=function_name(input 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 .

b) f ( x) for x = 1,3, 5, 7,9, and 11 .

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 .

Comparison between Script Files and Function Files:

• Both script files and function files are saved with the extension .m

• The first line in a function is the definition line

• 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

• Script files contain a sequence of MATLAB commands (statements)

• 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.

In cases when the value of a relatively simple mathematical function has to be


determined many times within a program, MATLAB provides the option of using
inline functions. An inline function is defined within the computer code (not as a
separate file like a function file) and is then used in the code. Inline functions can be
defined in any part of MATLAB.

Inline functions are created with the inline command according to the following
format:

name=inline(‘math expression typed as a string’)

• The mathematical expression can have one or several independent variables.


• Any letter except i and j can be used for independent variables in the
expression.
• The mathematical expression can include any built-in or user-defined
functions.
• The expression must be written according to the dimension of the argument
(element-by-element or linear algebra calculations).
• The expression can not include preassigned variables.
• Once the function is defined it can be used by typing its name and a value for
the argument (or arguments) in parenthesis.
• The inline function can also be used as an argument in other functions.

Inline function with one independent variable


2
ex
For example, the function f ( x) = can be defined (in the Command Window)
x2 + 5
as an inline function for x as a scalar by:

>>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)’)

>>FA([1 0.5 2])

M-FILES 28
P04700 COMPUTATION AND MODELLING

Inline function with several independent variables

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.

For example, the function f ( x, y ) = 2 x 2 − 4 xy + y 2 can be defined as an inline


function by:

>>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) .

The distance between two points A ( xA , y A ) and B ( xB , yB ) in a plane is given by:

d= ( x A − xB ) + ( y A − y B )
2 2
.

M-FILES 29
P04700 COMPUTATION AND MODELLING

The feval Command

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:

variable=feval(‘function name’, argument value)

The value that is determined by feval can be assigned to a variable, or if the


command is typed without an assignment MATLAB displays ans= and the value of
the function.

• The function name is typed as a string.

• The function can be a built-in or a user-defined function.

• 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

1. Write a user-defined MATLAB function that converts torque given in


units of lb-in. to torque units of N-m. For the function name and
arguments use Nm=lbintoNm(lbin). The input argument is the torque
in lb-in., and the output argument is the torque in N-m. Use the function to
convert 500lb-in. to units N-m.

2. A two dimensional state of stress at a point in a loaded material is defined


by three components of stresses σ xx , σ yy , and τ xy .

σ 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 

Write a user-defined MATLAB function that determines the principal


stresses from the stress components. For the function name and arguments
use [Smax,Smin]=princstress(Sxx,Syy,Sxy). The input
arguments are the three stress components, and the output arguments are
the maximum and the minimum stresses.

Use the function to determine the principal stresses for the following states
of stress:

a) σ xx = 150MPa , σ yy = −40MPa , and τ xy = 80MPa .


b) σ xx = −12ksi , σ yy = −16ksi , and τ xy = −7ksi .

3. Write a user-defined MATLAB function that calculates a student’s final


grade in a course using the scores from three midterm exams, a final
exam, and six homework assignments. The midterms are graded on a scale
from 0 to 100, and each accounts for 15% of the course grade. The final
exam is graded on a scale from 0 to 100 and accounts for 40% of the
course grade. The six homework assignments are each graded on a scale
from 0 to 10. The homework assignment with the lowest grade is dropped,
and the average of the remaining assignments accounts for 15% of the
course grade.

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

You might also like