IT1005 Reference Sheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

1.

Binary system of numbers


Tuesday, 16 August, 2011
4:57 PM

Boolean Logic
AND (.) , OR (+) , NOT (') operator

Binary system
int is a number with no fraction portion (i.e. integer)

Converting int from decimal to binary


Repeated division of decimal number until 0 is achieved.
Note: 1 is divided into [0 remainder 1]
Binary number is then read from Most significant bit (MSB) to Least
significant bit (LSB) , i.e. bottom up.

Binary is converted back to decimal by taking the numbers multiplied by


2x, where the LSB is multiplied to 20.
The sum of the products gives the decimal number

Converting fractional portions to binary


Isolate the fractional part, then repeatedly multiply by 2.
The first integer is the carry, and the process repeats by taking
the fractional portion only (remove the carry) and multiplying
till 1.0 is achieved.

Binary number is read from top down

Converting back to decimal by multiplying by 2-x , where the


first digit is multiplied by 2-1

Storing real numbers as floats

Scientific notation:

Numbers are then stored in either single float or double float:

IT1005 Page 1
Numbers are then stored in either single float or double float:

The number of bits in mantissa and exponent are limited by number of bits used, ∴ some precision will eventually be lost
- More bits in mantissa means more accurate data
- More bits in exponent means larger range of numbers can be represented

The first 1 is not stored in mantissa since first digit is


always a 1

Due to truncation of mantissa, positive real numbers


stored in double float is usually slightly smaller than
actual number

IT1005 Page 2
2. Simple MATLAB commands
Thursday, 18 August, 2011
3:11 PM

Basic Arithmetic Operators

\ back slash is divide with numerator behind and denominator in front. e.g. 2\10 = 5, while front slash / e.g. 2/10 = 0.2

Operations are carried in this order: Brackets, Orders (powers), Division/Multiplication, Addition/Subtraction

Variables

Variables are "named containers" that can store values


Default variable is "ans", which stores results of last operation
Get the value of a variable by typing its name

Create own variables using <variable name> = <value>

Separate variables with a " ; " to prevent it from printing (i.e. suppress output).
Use " , " to allow it to print when you press enter (i.e. show output).
Calculation can be done using the variables

who : print all currently stored variables


whos : print all currently stored variables with more details

Rules on Variable names


Case sensitive: "Cost" and "cost" and "coSt" are different variables
Limit of 63 characters, anything beyond are ignored
Must start with a letter, but can be followed by digits, letters or underscore ; no punctuations or space allowed
∴ always use short names, all in lower case, and avoid using keywords of commands in Matlab

isvarname : test if a variable name is acceptable


note the single quote [ ' ] used

ans can be used in calculations:

result = 2*2 + (2 + 3) = 9

IT1005 Page 3
Special Variables
pi : value of π; can be used in calculations [e.g. sin(pi) ]
eps :
inf : infinity [e.g. >> 1/0 ans = inf]
NaN : Not-a-number [e.g. >> 0/0 ans = NaN]
i : square root of -1 [e.g. >> i ans = 0 +1.0000i]
j : same as i
realmax / realmin : largest/smallest usable positive real number ( as limited by double/single float system)

clear : removes all variables


clear <variable name> : removes the specified variable
clear all : removes all variables and functions

clc : Clear Command window (without clearing variables)


clf : Clear figure / plots

Comments and Punctuations


Both ; and , can be used to separate multiple assignments, but most of the time we want to suppress output as we only want t o show
the final result

% : used for comments [e.g. add comments to remind what a statement does]

… : "ellipsis" symbol used to imply continuation of command onto next line [ useful for long commands]

ellipsis must come in between variables and operators

IT1005 Page 4
ellipsis cannot occur in the middle of a variable name

MATLAB Pre-defined functions

help elfun : help on elementary math functions


help datafun : help on data analysis functions

sqrt ( ) : square root. Can be used on a number or a series of numbers in a matrix/vector. Remember to include brackets
max ( ) : max value. Can be used to identify both max number and its position (index). see example below

mean ( ) : mean value


std ( ) : standard deviation
sort ( ) : sort in ascending order
sort ( [ ] , 'descend') : sort in descending order

sum ( ) : sum of values


prod ( ) : product of values

hypot ( x,y ) : Calculates Hypotenuse using Pythagoras theorem given 2 other sides. Equivalent to sqrt( x^2+y^2)
mode ( [ ] ) : Gives the mode (most frequent value) from a vector/matrix
floor ( ) : Rounds the value downwards to nearest integer
ceil ( ) : Rounds the value upwards to nearest integer

IT1005 Page 5
Input function
<variable> = input ( ' <prompt> ' ) : input function forces Matlab to provide a prompt for user to enter value for a variable
<variable> = input ( ' <prompt> ' , ' s ' ) : add a , ' s ' to enter a string (i.e. text) instead of value

Output function
Ways to control display of output
type in variable name without semicolon : displays variables

disp ( ) : displays variable values without variable names

disp (sprintf ( ) ) or fprintf ( ) : Display text and numbers together in same line

%d : print x as integer
%3d : add space to make field width of 3 characters
%.2f : print x as floating point, 2 digits precision
%6.3f : print x as float, field-width 6 characters, 3 digit precision
\n : print a new line character

IT1005 Page 6
3. Matrices
Sunday, 21 August, 2011
8:45 PM

Simple Vectors

Vectors : 1Xn or nX1 matrices


Matrix / Array : mXn matrices

x = [ 0 0.2pi 0.4pi 0.6pi] : use square brackets to denote the start and end of a vector. Separate elements using space or comma
used to create vector of user-assigned values
this is known as a row vector ( 1Xn matrix )
y = [ 0; 2; 4; 5; 6] : rows are separated by semicolon . this is known as a column vector ( nX1 matrix )

Range Indexing
x (3) : Recalling the 3rd element in matrix x, aka index . Format: <matrix name> ( <index> ) .
Value can also be edited by putting e.g. x (3) = 10

Using whos <matrix name> will display the number of elements in the matrix (e.g. 1X6)

z = x ( 2:5 ) : Create matrix z containing elements 2 - 5 of matrix x. x (2 : 5) can be used to specify the 2nd - 5th elements

z = x ( 2 : end ) : Use end to specify last element

z = x ( [ 2 3 6] ) : List the individual indices as vector to get a matrix with the 2nd, 3rd and 6th element

Creating simple vectors

x = ( <start> : <increment> : <end> ) : Create vector with automatically assigned elements, value ranges from start to end with fixed
increment between elements
e.g. x = ( 0 : 0.001pi : pi ) creates a vector x from 0 to π, with increments of 0.001π
Note: the brackets ( ) can be omitted, but are included to make it appear more tidy.
Note: the number of elements in the vector cannot be controlled directly
Note: If increment is not specified, default increment is 1

IT1005 Page 7
Note: If increment is not specified, default increment is 1
x = linspace ( <start> , <end> , <no of elements> ) : creates vector with no of equally spaced elements, from start to end
e.g. x = linspace ( 1 , 2, 6 ) creates a vector x from 0 to 2 with 6 equally spaced
elements
Note: If no. of elements not specified, default no. of elements is 100
x = logspace ( 0, 2, 10 ) : Creates vector with logarithmically spaced elements, starting value 100 , ending value 102 , with 10 elements
Note: If no. of elements not specified, default no. of elements is 50

z = [ ] : Use of square brackets allow you to join or concatenate vectors together

Note: Use of [ ] will slow down processing, hence use ( ) unless necessary

When saving file, do not put space in the file name. If not, this will cause error to appear when trying to execute the code from
command window

%% : Inserts a cell break while inserting a comment (similar to %). Note to include a space behind %% for the cell break to work.

Cell break is shown as a line across the Editor. Only works in M-file

If A = ( 1 : 1: 100 ) i.e. vector of 1 to 100 , vector B can be created B = A ( 3: 3 : 100) creating a vector from the 3rd element and
increment of 3 elements till the 100th element of A, i.e. vector of numbers divisible by 3

Creating Matrices
Use space or , to separate elements in a row, and use ; to separate rows
e.g.

size (A) : Prints the number of rows and columns in matrix A, in the format ans = <no. of rows> <no. of columns>
numel (A) : Prints the number of elements in matrix A , in the format ans = <no. of elements>

Indexing of Matrices

Matlab stores matrices column by column, therefore the index of elements is in this order:

When recalling index, index runs from column to column

x (:) : the (:) command linearizes the matrix into a column vector, e.g.:

IT1005 Page 8
x ( 1 , : ) : the : symbol can also be used to retrieve/refer to all elements in a particular row / column. e.g. this command retrieves all
elements in row 1 of matrix x

x ( : , [ 1 3 ] ) : Retrieve all elements in all rows from columns 1 and 3 (skip column 2)

A ( 2 , 3 ) = 0 : Assign the element in row 2 and column 3 to be 0 (or any user-specified value)
A ( : , 2 ) = 3 : Change all the elements in all rows in column 2 to be 3
A ( 3 , : ) = 9 : Change all the elements in all columns in row 3 to be 9

Replacing an entire row / column with another vector:

Deleting an entire row / column , i.e. replace with an empty array :

←Note: A single element cannot be deleted as this will


cause a 'hole' to appear in the matrix which is not
possible

Scalar-Matrix Arithmetic
x - 2 : minus 2 from every element in matrix x
2*x - 1 : Multiply every element in x by 2 , then minus 1 Note: Do not put 2x as Matlab requires * to indicate multiply
x / 2 : Divide every element in x by 2. Note that 2 / x does not work

This scalar arithmetic processes are also


known as "scalar expansion"

Matrix-Matrix Arithmetic

IT1005 Page 9
Matrix-Matrix Arithmetic
x + y : Adds matrix x to matrix y, provided that both are of identical dimensions
x . * y : Multiplies every element in matrix x by its corresponding element in matrix y. Note the use of period to perform element-by
element operations
x . / y : element- by-element division of x by y

x * y : Matrix Multiplication between x and y, provided that matrix x and y have inner matrix dimensions that agree
e.g. x (aXb) * y (bXc) = z (aXc)

Matrix Inversion
x / y : x * inverse (y)
x \ y : inverse (x) * y

x .^2 : squares individual elements in matrix x


x .^ y : takes each element in x and raises it to the power of the corresponding element in matrix y
2 .^ x : creates a matrix of 2x , where x is the corresponding element in matrix x

x ^ 2 : this operation is the same as x *x , and will produce an error if the inner dimensions of x do not agree, e.g. (2X3) * (2X3)

Summary

Transpose
x' : the ' symbol transposes the matrix x

When applied to vectors, it turns column vectors into row vectors and vice versa

When applied to matrices, it turns every column into a row and vice versa
therefore, a (2X3) matrix becomes a (3X2) matrix

IT1005 Page 10
Standard Matrices
ones (n) : Creates a nXn matrix of 1's
ones ( r , c ) : Creates a rXc matrix of 1's

Similarly, zeros and rand and randn are used in the same way:

↑ Note: As the elements in randn are all random numbers, the mean and standard deviation will only be close to 0 and 1. Values get
closer as the number of elements in the matrix increase

repmat ( d , r , c ) : Creates a matrix with r rows and c columns, with constant d as every element. repmat stands for 'replicate matrix'
←all 3 methods create the same matrix, but
repmat is the fastest function

IT1005 Page 11
4. Process Flow
Sunday, 4 September, 2011
7:11 PM

Relational operator
< Less than
> Greater than
<= Less than or Equal
>= Greater than or Equal Note the order of the 2 symbols
== Equal to Note: a single = is used to assign values to variables, double equal is EQUAL to operator
~= Not Equal to Tilde equal

Matrices or Scalars can be compared using the relational operator, and the answer is given as TRUE (logical 1) or FALSE ( 0 )

Answer is given as TRUE or FALSE for each of the elements in the matrix
Note: tf here is a created variable
Matlab can treat this logical array as real 1's and use them to add/subtract to other matrices

Any non-zero number is treated as TRUE in Matlab. Therefore, any vector or matrix of numbers can be used as a logical array

abs( ) : take absolute

Due to floating point system, 2 terms that are the same arithmetically may have small difference (due to loss of precision)
Take absolute difference between the 2 terms and compare with eps to test for zero
If absolute difference between 2 terms is smaller than
eps, treat the 2 terms as equal
Note: value of eps (2.2204e-016) can be adjusted to suit
the sensitivity of code

Logical Operators
& AND TRUE only if both are TRUE
| OR TRUE if either or both are TRUE
~ NOT converts TRUE to FALSE, vice versa
&& Scalar AND with short circuit evaluates first part, if already FALSE, it will not compute 2nd part (lazy evaluation)
|| Scalar OR with short circuit evaluates first part, if already TRUE, it will not compute 2nd part (lazy evaluation)
Note: Short circuit operators only work on scalars, and since the first result determines the outcome, the 2nd part is not evaluated in
some cases. In cases where 1st part cannot determine result, both parts will be evaluated.

Short circuit operators are useful in e.g.:


code checks if b=0 first, before computing second part. If b = 0, the second part is not
computed to prevent "division by zero"
Another useful scenario:

Check N if it is >1000000 first before executing isprime(N), which takes a lot of time
Note: sequence of code is important. code is much slower if isprime(N) is executed
first

Operator Precedence

IT1005 Page 12
Operator Precedence

Note: Parentheses have the


highest precedence, ∴ always use
them when something needs to be
executed first

Note: the order affects which


operations are executed first,
which may affect the final answer

Find Function
find ( ) : returns the indices of non-zero elements, e.g.:

Logical operator gives TRUE (1) and FALSE (0)


Only those with 1 are returned
Create new variable I to contain the indices

Use A(I) to recall the elements itself

Alternatively, to return the elements itself, use the logical array to recall:
←Special extraction of MATLAB, when a logical array is entered to retrieve the
elements, MATLAB recognises the logical array and retrieves only the TRUE values (or
values that have truth value 1 in the logical array

find( ) also works on 2D matrix, but remember the indices recalled are based on column by column. Similarly, use M(I) to recall the
elements itself

Given a 2D matrix, you can recall the row and column of the non-zero elements instead:
[ r c ] = find ( A>7 ) : Returns the rows (stored in dummy variable r) and column (stored in dummy variable c ) of the non-zero
elements

←Results returned show there are 2 elements, at (row3,col2) and (row3,col3)

[ r c ] = find ( A>7 , 1 ) : add the 2nd argument to return only the 1st non-zero element

IT1005 Page 13
Logical Functions
any ( ) : Returns TRUE (1) if at least one element is non-zero
all ( ) : Returns TRUE (1) only if all elements are non-zero

NaN : When a undefined answer is returned, the value is stored as NaN (Not-a-Number), e.g.:

However, is returned as Inf, for all values of x

Note: NaN == NaN returns FALSE, therefore, to check if a function returns NaN, use:
isnan ( ) : Returns TRUE (1) if element is NaN

isempty ( ) : Returns TRUE (1) for a empty matrix [ ] . Use this test to check if function returns empty matrix (e.g. no values returned)

Repetition: FOR-loops
for-loops iterates over the columns of a specified matrix
Syntax:
for var_name = row_vector
operations/commands
end

e.g.:
for A = [ 1 2 3 ] ← For every 1 element/column in the for matrix, Matlab will execute the command
A = A + 10 (e.g. A = A+10) once and print results, if any
end
∴ Matlab will repeat the command as many times as the number of columns in the for
Returns: matrix
A = 11
A = 12 Note: the command below need not necessary involve the for matrix, ∴ for matrix can
A = 13 be just used as a count of no. of times to repeat command

for-loops also works on 2D matrix, but each iteration takes the entire column at a time, which may not be desirable

This can be overcome by using nested for-loops:

e.g.: ←3X3 matrix


A = [ 1 2 3; 4 5 6; 7 8 9 ]; Note: a and b are dummy variables.
for a = 1:3 When nested together and using "A(a,b)" or "A(b,a)" , you can
for b = 1:3 ←The inner loop will continue looping control whether to return based on columns first or rows first.
A (a,b) first, until all columns in b are printed.
end Then it will go to column 2 of a and
end inner loop will then loop again till all
columns
Benefits of for-loop: No. of repetitions (iterations) can be known and controlled; iterations is done over columns of specified matrix
(usually row vector)

Repetitions: WHILE-loops
Syntax:
while-loops while a certain condition is fulfilled.
while condition 1
i.e. if condition 1 is fulfilled, operations 1 will be executed, then condition 2 will
operations/commands 1
be checked if it is fulfilled
while condition 2
while-loops can also be nested in this syntax.
operations/commands 2
end
Note the indents used in nested loopings
end

Selection: if … else … end


Syntax:
Nested if ...else...end
command can be entered
after else to be executed if
← else and if can be
condition 1 is NOT met.
combined to elseif

IT1005 Page 14
← else and if can be
condition 1 is NOT met.
combined to elseif

e.g.:

break : used after if to prematurely end the loop if condition 1 is fulfilled, i.e. the element and any element after it will not undergo
command in the loop
continue : used after if to skip iteration for this element if condition 1 is fulfilled, e.g.:

Selection: switch … case … end


Used as a alternative to if … else … end when there are too many cases to consider

Syntax:
switch x
case values of x for case 1
operation 1
case values of x for case 2
operation 2
otherwise (this is optional)
operation 3
end

e.g. in replacing if … else … end syntax: Note the difference in


indenting.
← Note that switch … case
→change syntax →
syntax is able to check for
multiple conditions at once

Multiple conditions have


to be put in :
{ condition1 , condition2 }

Benefits of switch … case … end syntax:


- shorter to code
- can check for multiple cases at the same time
- can be used to compare strings input (see example) [in contrast, if … else syntax requires function "strcmp" to compare strings

IT1005 Page 15
- can be used to compare strings input (see example) [in contrast, if … else syntax requires function "strcmp" to compare strings
of different character length]

e.g. : code to convert user input grades into points

Note: addition of ,'s' to the input argument


to enter strings instead of numbers

subsequently, the case must also have ' ' to


indicate comparing of strings

Selection: try … catch … end

Syntax:
try
the command that could give an error
catch
commands to execute if command gives an error
end

This syntax can be used to print customised error messages in the event of an error (using disp(error msg) or fprintf(error_msg) as
command)
It can also be used to re-prompt user to input a valid value for the variable, (using input('value of x') as command)

lasterr : returns ans = the last error message printed


lasterror : returns ans = the last error message printed with error details

IT1005 Page 16
5. Top down design
Thursday, 8 September, 2011
3:00 PM

l5-top-down
-design
Inserted from: <file://C:\Users\JW Ng\Documents\Work Folder\Sem 1 2011-2012\IT1005\Lecture notes\l5-Top-Down-
Design\l5-top-down-design.pdf>

IT1005 Page 17
IT1005 Page 18
IT1005 Page 19
IT1005 Page 20
IT1005 Page 21
IT1005 Page 22
IT1005 Page 23
IT1005 Page 24
IT1005 Page 25
Histogram

IT1005 Page 26
IT1005 Page 27
IT1005 Page 28
IT1005 Page 29
IT1005 Page 30
IT1005 Page 31
IT1005 Page 32
IT1005 Page 33
IT1005 Page 34
IT1005 Page 35
6. Graphical Tools Notes
Sunday, 9 October, 2011
5:33 PM

plot ( Y ) : If Y is a column or row vector, MATLAB interprets it as plot( 1:length(Y) , Y ) , i.e. no. of elements in Y as x-axis
If Y is a matrix, MATLAB interprets it as plot (1:size(Y, 1) , Y ) , i.e. no. of columns in Y as x-axis
If Y is a matrix containing complex numbers (e.g. 4 + 2i), MATLAB interprets as plot ( real(Y) , imag(Y) ), i.e. real part of Y in x-
axis and imaginary part of Y in y-axis
e.g.

Points are joined based on the order in which they are listed in the matrix

plot ( X1, Y1 , X2, Y2, … ) : MATLAB plots X1 against Y1 and then X2 against Y2 and so on. Different graphs are plotted on the same axis in
different colours (default first is blue, second is green)

If one of the inputs (X or Y) is a matrix, MATLAB will plot each row of the matrix against the vector, producing
multiple graphs similar to if each row of the matrix is saved as Y1 , Y2, etc.

hold on : keeps the existing graph (i.e. the graph plotted before the hold on line) such that when a subsequent plot is called, the new
graph is drawn onto the existing axes. If data does not fit into existing axes, the axes are then rescaled.
Note: the new graph drawn will ALSO be in blue, so the formatting must be changed to differentiate the 2 plots

plot( X, Y, 'o-' ) : 3rd argument added (in ' ' as a character string) to indicate line colour, style and/or marker

for example:
'mo-.' plots a magenta line
with circle markers and
dot-and-dash line

IT1005 Page 36
In addition, further arguments can be added to change more properties,
e.g. … , 'LineWidth', 2 , … changes the line width to 2 pt
, 'MarkerEdgeColor' , 'k' , … changes the edge of markers to black
, 'MarkerFaceColor' , [.49 1 .63], … changes the fill of markers to green (according to the RGB array provided)
, 'MarkerSize', 12, … changes the size of the marker to 12 pt
, 'Color' , [R G B], … changes the colour of the line to the colour specified by the RGB array, where R, G, B can be scalar
variables
grid on : Turn on grids at the tick marks
grid minor : Turn on minor gridlines between tick marks
xlabel ( ' Expenditure ' ) : adds label to x-axis
ylabel ( ' Month ' ) : adds label to y-axis
title ( ' Spending per month ' ) : adds title to graph
legend ( ' This month ' , ' Last month ') : adds legend to graph. Strings label the graphs in the order they are entered.
text ( X , Y , ' string ' ) : adds a string text to location (X,Y) of a plot. X and Y may be vectors, then the same string is printed on all
locations. string can also be an array with same no. of rows as X and Y, then the corresponding text will be
printed at each location

title and xlabel, ylabel may be combined with sprintf if formatting of strings are needed
e.g. title(sprintf(' The total expenditure is %.3f ' , sum_spent ))

Fancy text

To add percentage sign, key %%


to add backslash, key \\

Superscript by adding ^ , Subscript by adding _


To add the symbol itself, prefix it with a backslash
e.g. \^ prints the carat symbol

IT1005 Page 37
Subplot
subplot ( m , n , p ) : Divides the current figure window into a m-by-n matrix of plotting areas and chooses the pth area to be active
e.g.

splits the figure into 4 areas and selects the 3rd area. Hence the 'Benny' plot is plotted in the 3rd area
any code following the subplot will affect only the selected area, until another subplot is called
Note: subplot (2, 2, 1:2) chooses the 1st and 2nd area to be active, hence the plot will take up 2 areas (long rectangle)
Note: the numbering of the areas goes row by row, left to right.
(different from matrix indexing, which is column by column)

Deleting a data point


Delete a certain data point by setting it = NaN. e.g. Y(4) = NaN , will delete the 4th element and hence will not be displayed in the graph

Altering graph properties


set ( gca , 'XTick', [ 1 2 3 4 6 ] ) : set changes the property selected, gca gets the handle of the current axis, while the vector listed is
used as the X Ticks (value markers on the axis)
e.g.

'YTick' is used to change the Y ticks on the Y-axis

axis equal : make the scale of X and Y axis equal


axis ([ -1 1 -2 0 ]) : sets the axis using defined values, keyed in in this order: min x (left most value of x) , max x , min y , max y

IT1005 Page 38
7. Linear Algebraic Equations
Sunday, 9 October, 2011
7:27 PM

Identity Matrix

eye ( n ) : creates a n X n identity matrix ( I )


e.g.

Note: A * I = A = I * A A * A-1 = I
Note: any matrix A has an inverse only if it is a square matrix and its determinant is non-zero (i.e. non-singular)

det ( A ) : returns the determinant of matrix A


inv ( A ) : returns the inverse matrix of matrix A
B = inv ( A ) : stores the inverse matrix as a new matrix B

rand ( n ) : returns a non-singular random n X n matrix

Matrix Calculations
For a equation Ax = B , where A, x, B are all matrices/vectors
x = A-1B
In MATLAB, this can be done by 2 ways:
x = inv(A) * B : calculates inverse of A and multiply by B

x = A \ B : use of backslash is equivalent to pre-multiply by inverse. This code is FASTER and more accurate than the 1st method.

IT1005 Page 39
7. Symbolic Mathematics
Sunday, 9 October, 2011
8:34 PM

syms a b c x : creates 4 symbolic objects a, b, c, x


sym x : creates 1 symbolic object x [Note: difference is sym can only define 1 at a time]

f = a*x^2 + b*x + c : create a symbolic object f containing the other symbolic objects
Note: whos will return all these symbolic objects

sym can also be used on numbers to


express rational fractions

Differentiation
diff ( f ) : differentiate f with respect to x ,
or in the absence of x, the next closest letter to x, downward first in case there is a tie (e.g. between w & y, y is chosen)

diff ( f , n ) : differentiate f with respect to x n times, i.e. get the nth order differential of f

diff ( f ,a, n ) : differentiate f with respect to a n times. i.e. 2nd argument is the variable to differentiate with respect to

simplify ( ans ) : expresses the ans in nicer forms, e.g. surds are represented as 5^(1/2) instead of in decimals

pretty ( ans ) : expresses the ans in "hand-written maths" form, in terms of matrix, fraction and indices representations
e.g. :

Limits
limit ( f , h , 0 ) : calculates limit of function f , as variable h tends towards 0, i.e. 1st argument is the function, 2nd is the variable that we
are taking w.r.t. , 3rd is the value that the 2nd argument tends to
e.g.

can be entered as :

limit ( f , h , 0 , 'left') : take limits , approaching from 'left' , or from 0-


e.g.
can be entered as :

can be entered as :

Integration
int ( f , 0, pi/2 ) : Integrate f (with respect to x) from 0 (lower limit) to π/2 (upper limit)

Solving equations

IT1005 Page 40
Solving equations
solve ( f ) : solves the variable f , returning value of x when f = 0, e.g. solving quadratic equation
Note: g = solve ( ' a*x + c = b*x ' ), for solving equations in the form f(x)=q(x), quotation marks ( ' ' ) must be used

Plotting symbolic equations using ezplot

Note the default domain is -2π< x < 2π


unless otherwise entered

IT1005 Page 41
8. User-defined Functions
Sunday, 9 October, 2011
10:48 PM

Syntax

function [rv1 rv2 … ] = functionname ( par1 , par 2 )


% insert help message here

MATLAB code (e.g. formula in terms of par1)


rv1 = expression ←function needs to be used. Function is called in
Command Workspace using the name it is saved, not
Example the function name in the code! (even though normally
it is saved in the same name to avoid confusion)

← help message can be entered for function. Blank rows can be entered by
using %. Help message terminates at the first non-% row of code

help message normally starts with CAPS for the function (following MATLAB's
predefined function style)

Code to manipulate the input until the


output is achieved.
Code should end with allocating a value
for the "return variable" ret

Note: User defined Functions (UDF) is normally not named using existing predefined function names, if not original function will be
overwritten.
Note: function naming has the same rules as variable naming:
- must begin with letter, followed by numbers or letters or underscore

Variables defined within functions cannot be recalled from the Command Workspace.

pow = pow +2 : only odd terms


sign = sign * -1 : faster way to create alternating positive and negative terms, similar to (-1)n in maths

factorial( n ) : returns the factorial of n

Returning Multiple Values


define output as a vector of multiple values to
return multiple values

Multiple outputs can be recalled by using the following ways:


1. >> [ y z ] = userfunction( input) : using 2 variables to store the answer when using the function
2. within the function code, ret = [ return1 ; return2 ] : store the output as a vector of multiple values, so when the answer is called,
multiple values are printed

error ( 'string' ) : stops MATLAB function and prints the string as warning message if the preceding condition is met

warning( ' string ' ) : prints the string as warning message if the preceding condition is met (does not stop code like error)

IT1005 Page 42
warning( ' string ' ) : prints the string as warning message if the preceding condition is met (does not stop code like error)

when function code does not have any equal sign, no value is
returned.

to use such a function, do not specify output variable

Note: to see if a variable n is within a group of values, use the following codes:
example n = 3
we want to check if n is within group of numbers: 2, 3, 4

n == [2 3 4] returns a logical array [ 0 1 0 ],

1. so using any( ) checks if there are any non-zero values within, and returns TRUE if there
are

2. using find( ) returns the index of the element that is the same as n. Can be used with if to
produce TRUE result

IT1005 Page 43
9. Solving for roots, minimum (optimisation), Curve Fitting
Saturday, 29 October, 2011
9:35 PM

Solving for roots using fsolve


syntax

g = fsolve( @functionname , initial_guess )

g is a variable we create to hold the root of the solution.

functionname is a user defined function that is created based on the equation we are trying to solve

@ is the function handle and is used to call out the UDF

initial_guess is supplied to start the process of root-finding, normally from ideal approximations (e.g. ideal gas equation)

Creating UDF from an equation

Create a function code by shifting all terms to one side, i.e. the other side = 0

1. Create the function in terms of the inputs v, T, P


(This is also known as anonymous function)
2. Enter all fixed variable values

3. f = equation

Syntax for solving Anonymous functions


Input the other variables (except the one we are finding)

fsolve( @(variable) functionname( var1, var 2, var3 ), initial_guess )

↑note the bracket around the variable, and the space after variable

Solving Systems of Non-Linear Equations using fsolve


1. rewrite equations such that one side = 0

2. Let x = v(1), y = v(2), where v is the 2X1 vector input to the function code

3. Output F is also a 2X1 vector, where the first element F(1) = first equation in terms of v(1), v(2) and F(2) = second equation

← each element of F is calculated separately (diff equations)

4. solve for x , y in Command Workspace, by giving 2 initial guesses for x and y and using 1 variable to store the output

using ans to store output


or
create a variable ans_vector to store the output

IT1005 Page 44
create a variable ans_vector to store the output

Output:

Expressing Mathematical operators


exp( x ) : ex
log( x ) : ln(x) , natural log
10^( x ) : 10x
log10( x ) : lg(x) , common base 10 log
acos( x ) : cos-1(x) , inverse cosine

Solving Polynomials using roots and fzero


fzero : Solves only single nonlinear equation; requires initial guess and gives only 1 root per guess

note: function handle requires the


@ before function name

roots : Solves only for polynomial equations, gives ALL roots; no initial guess needed

input vector C contains the coefficients of


the polynomial from highest order of x to
the constant

Optimisation
Unconstrained optimisation using fminsearch
1. Express equation into function file
2. Single variable functions f(x)

>>fminsearch( @equation, initial_guess ) : returns 1 output which is the value of x (variable) when function becomes a
minimum

>>[ x, f ] = fminsearch( @equation, initial_guess ) : use 2 variables to store output. x will store the variable value while f will
store the function value, f(x), when it is at the local minimum

Multi-variable functions f(x,y)

the function code similarly expresses x = x(1) , y = x(2) , then 2 initial guesses for x and y have to be supplied as a vector
>>[ x, f ] = fminsearch( @equation, [initial_guess_x, initial_guess_y] )

↑ x will be a 2X1 vector containing x and y values at local minima, while f is a scalar containing f(x,y) at local minima

Note: fminsearch, and any other code, cannot identify which is absolute minimum, so try several initial guesses within range to find
which is the absolute (lowest) minimum

Finding roots using fminsearch:


add abs( ) to the equation function so that zeros end up as minima for the graph, results same as fsolve

Finding maximum using fminsearch:


add negative sign to equation function so that graph is flipped and maxima becomes minima when searching
Note: f(x) value found in this case will also be negative

Constrained Optimisation using fmincon


Example to illustrate Optimisation Constraints:

IT1005 Page 45
Example to illustrate Optimisation Constraints:

1. Write objective function (equation we are trying to minimise/maximise into function M -file:

2. Organise Inequality Constraints into vectors, and then Equality Constraints into vectors, then Upper and Lower Bound
constraints into vectors

A is a matrix while B is a vector

3. >>[ x , f ] = fmincon(@function_name, [ initial_guess_x1 ; initial_guess_x2 ], A , B, C, D, LB, UB )

where: A, B are Inequality constraint vectors


C, D are Equality constraint vectors
LB, UB are vectors containing Lower Bound, and Upper Bound

2 initial guess have to be supplied in a column vector


If there are no Equality Constraints, replace the input with [ ], [ ]
Order of inputs is important, though empty inputs behind can be omitted

Output: x will be a 2X1 vector containing the optimised amount of x1 and x2, while f is a scalar for the optimised profit

Curve fitting
Finding the best fit polynomial approximation using polyfit

IT1005 Page 46
Finding the best fit polynomial approximation using polyfit

polyfit returns a vector P containing the coefficients of the polynomial (of order N) that describes the best fit curve for the data x , y

Evaluating best fit estimation for Y-value using polyval

polyval requires an input vector P (achievable through polyfit) , and a scalar/vector X , and returns the estimated values of Y

IT1005 Page 47
10. Ordinary Differential Equations (ODE)
Sunday, 30 October, 2011
11:32 AM

Differential equation is an equation that gives the derivative ( )

differential equation and marching formula

Solving ODE using ode45


Single variable ODE
1. Code differential equation into function M-file
The function must accept 2 inputs: Time and Initial Condition of Independent Variable (e.g. x at t = 0 )

Output of function must be the derivative itself

2. >>[ t , v ] = ode45(@function_name , time_span , initial_condition )


where time_span is a row vector containing the time to calculate over, e.g. [ 0 10 ]
initial_condition is a scalar, the initial condition

Output t will be a vector containing all the time slices taken by ode45, v will be a vector containing all the values of the variable at
the respective time t

Multiple variable ODE


1. translate the 2 coupled ODE , e.g.:

become 2 ODE in 2 variables


displacement s = y1
Velocity v = y2

Code the equations into a function M-file


Input is Time, and a Column Vector Y containing the Initial condition of y1 and y2 e.g. y = [ 0 ; 0 ]
Output must be a Column Vector containing the value of derivatives
e.g.:

the output must be transposed to become a column vector

2. >>[ t , v ] = ode45(@function_name , time_span , initial_condition )


where time_span is a row vector containing the time to calculate over, e.g. [ 0 10 ]
initial_condition is a column vector containing the initial conditions of all the variables y1, y2 at the same time instance

Output t will be a vector containing all the time slices taken by ode45 , v will be a matrix containing the value of each variable y1
and y2 in separate columns at all the time t

Note: the time slices taken by ode45 are not uniform in spacing, and the no. of slices taken is dependent on the function (less variation in

IT1005 Page 48
Note: the time slices taken by ode45 are not uniform in spacing, and the no. of slices taken is dependent on the function (less variation in
output value will cause ode45 to take a larger 'step' in time)

In general:

← time span
← initial conditions of each variable

← vector containing all the time slices

← matrix containing all the variable values

Classification of ODEs
Linear: No square terms in terms of y', y'' , no multiplication of 2 differentials
Homogenous: No explicit appearance of constant in the differential equation
First-order: No y'' or higher derivatives

Initial Value problem: Initial conditions are always specified at the same value of the independent variable (e.g. at same time t)
Boundary Value problem: Conditions given are at different value of independent variable

User-created ODE solver

IT1005 Page 49
Differences from ode45
- time slices are fixed
- uses explicit Euler method while ode45 uses the implicit Runge-Kutta method

Higher order ODEs


ODEs containing y'' or can be solved by expressing each differential order as a element in vector y
e.g.: y'' + 2y' + 2y = cos(2t)
Let y = y(1), y' = y(2) , therefore y'' =

Code ODE into n first order equations (where n is the order of ODE), last equation is the original ODE, preceding equations are all
definitions:

← "definition" equation
return variable dydt will contain the values of y' and y''
initial condition y will contain the initial conditions of y and y'

Solving Stiff Systems using ode15s


ode15s(@function_name , time_span , initial_condition ) : use to solve problems with 2 very different timeframes.
where time_span is a row vector containing the time to calculate over, e.g. [ 0 10 ]
initial_condition is a column vector containing the initial conditions of all the variables y1, y2 at the same time instance

ode15s works by realising when it has reached the peak of the system and then takes bigger "steps" when computing the slow decrease

E.g. of Stiff systems:

↑ exponential part decays rapidly with time, therefore will only appear in short time scale but not in long time scale

IT1005 Page 50
graph showing sharp rise (time frame 1) and then slow decrease (time frame 2)

IT1005 Page 51

You might also like