IT1005 Reference Sheet
IT1005 Reference Sheet
Boolean Logic
AND (.) , OR (+) , NOT (') operator
Binary system
int is a number with no fraction portion (i.e. integer)
Scientific notation:
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
IT1005 Page 2
2. Simple MATLAB commands
Thursday, 18 August, 2011
3:11 PM
\ 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
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
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)
% : 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]
IT1005 Page 4
ellipsis cannot occur in the middle of a variable name
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
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 (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
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 3 6] ) : List the individual indices as vector to get a matrix with the 2nd, 3rd and 6th element
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
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:
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
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
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 : 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
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.
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
Find Function
find ( ) : returns the indices of non-zero elements, e.g.:
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
[ 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.:
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
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
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.:
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
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]
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)
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
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)
IT1005 Page 38
7. Linear Algebraic Equations
Sunday, 9 October, 2011
7:27 PM
Identity Matrix
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)
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
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
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 :
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
IT1005 Page 41
8. User-defined Functions
Sunday, 9 October, 2011
10:48 PM
Syntax
← 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)
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.
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.
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
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
functionname is a user defined function that is created based on the equation we are trying to solve
initial_guess is supplied to start the process of root-finding, normally from ideal approximations (e.g. ideal gas equation)
Create a function code by shifting all terms to one side, i.e. the other side = 0
3. f = equation
↑note the bracket around the variable, and the space after variable
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
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
IT1005 Page 44
create a variable ans_vector to store the output
Output:
roots : Solves only for polynomial equations, gives ALL roots; no initial guess needed
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
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
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
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
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
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
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
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
IT1005 Page 49
Differences from ode45
- time slices are fixed
- uses explicit Euler method while ode45 uses the implicit Runge-Kutta method
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'
ode15s works by realising when it has reached the peak of the system and then takes bigger "steps" when computing the slow decrease
↑ 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