comp 116: introduction to scientific programming lecture 36: final review i
TRANSCRIPT
COMP 116: Introduction to Scientific Programming
Lecture 36: Final Review I
Final Exam Details
The final will be ◦Comprehensive◦Roughly like the midterms, but will
have more stuff ◦Short programs (5-10 lines of code)◦No linear programming, image
manipulation, audio filtering
Course objectivesTo teach you how to write code
◦We’ve mainly used MATLAB as a vehicle for this
int my_function(){ int data[ ] = {6, 3, 3, 8, 43, 2, 19, 7, 5, 88}; int num_elements = 10;
int res = data[0]; for (int i = 1; i < num_elements; ++i) { if (data[i] < res) { res = data[i]; } } return res;}
What does this function do?
Course objectivesTo teach you how to write code
◦We’ve mainly used MATLAB as a vehicle for this
◦…but the concepts you’ve learnt in this class carry over to almost every other programming language
Course objectivesWhat I hope you’ve learnt: If you have some data
◦Read it into MATLAB◦Process it in some way◦Display/plot it in some way◦Write out the results
Keep going!◦Many other great courses in Comp. Science◦ In today’s world, programming is a
fantastic skill to have
Important points:Operator precedence When in doubt use parenthesesSemicolon suppresses output
◦5+3; % does not create output◦5+3 % creates output
Matlab as a Calculator
Super-important: Distinguish between element by element operators and matrix operators.
Operators / Full Precedencedoc ops
Precedence
Operator
1 (high) Parentheses ( )
* Nesting (inner to outer)
2 Transpose .' or ' , Power .^ or ^
3 Unary minus/plus -, + Negation ~
4 Multiplication .* or *Right / Left division ./ or /, .\ or \
5 Addition +, Subtraction -
6 Colon operator :
7 Comparisons < <= == >= >
8 Logical ‘And’ &
9 Logical ‘Or’ |
10 Logical short-circuit ‘And’ &&
11 (low) Logical short-circuit ‘Or’ ||
* Left to right rule applies
Operators
Arithmetic:
Unary: -, +
Binary: +, -, *, /, \, ^ .*, ./, .\, .^ Assignment: =
Colon: :Logical: ~, &, |, &&, ||, XORRelational: <, <=, ==, ~=, >=, >
Special CharactersChar Name Usage
===
Equal Sign
: Colon
; Semi-colon
( ) Parenthesis
[ ] Brackets
{} Curly braces
. Period
' Apostrophe
% Percentage Sign
Special CharactersChar Name Usage
===
Equal Sign 1. Assignment2. Equality test
: Colon 1. <begin>:<step>:<end>
; Semi-colon 1. Suppress command output2. Start a new row in an array
( ) Parenthesis 1. Force Desired precedence in expressions2. Indexing Operator3. Used with function calls
[ ] Brackets 1. Create Arrays (Vectors & Matrices)2. Multiple outputs from function calls
{} Curly braces 1. Construct cell arrays2. Access cell array content (vs. accessing a
sub-cell array with () ).
. Period 1. Decimal point in floating point numbers2. Access field names in structures
' Apostrophe 1. Matrix transpose2. Construct Character array (string)
% Percentage Sign
1. Comments (%% == grouping comments)
Array & Vector Operations
Working with Vectors / Matrices
Colon Operator ‘:’ v = <start>:<stop>
v = <start>:<step>:<stop>
>> A = [1.1:1.1:4.4; 5.5:1.1:8.8; ...
9.9:1.1:13.2];
Linspace command:>> linspace(0,2*pi,100);
Indexing Operator ()A(7) % a(n) = 1D Indexing
A(3,2) % a(r,c) = 2D Indexing
Important Matrix FunctionsFunction Example Note
zeros zeros( 3, 5 )
ones ones( 4, 3 )
eye eye( 4 )
diag diag( [1 2 3 4] )
rand rand(5, 7)
size size( m )
length length( m )
numel numel(m)
' m'
reshape reshape(m,2,6)
repmat repmat(m,3,2)
<empty>
E = []
deletion E(2:4,:) = []
Important Matrix FunctionsFunction Example Note
zeros zeros( 3, 5 ) Creates m x n matrix of all zeros
ones ones( 4, 3 ) Creates m x n matrix of all ones
eye eye( 4 ) Creates n x n Identity matrix
diag diag( [1 2 3 4] )
Creates n x n matrix with vector on diag
rand rand(5, 7) Creates m x n matrix of random values
size size( m ) Returns Vector of size of each dimension
length length( m ) Returns scalar = maximum dimension size
numel numel(m) Returns total elements in matrix
' m' Transpose matrix (rows ↔ columns)
reshape reshape(m,2,6)
Reshapes matrix to new r x c layout
repmat repmat(m,3,2)
Builds large matrix from r x c copies of specified small matrix, IE ‘m’
<empty>
E = [] create an empty matrix or vector variable
deletion E(2:4,:) = [] Delete 2nd thru 4th rows from array
ConcatenationVectors and matrices can only be
concatenated if the number of rows/columns line up
[1 2 3; 4 5 6] % works
[1 2 3; 4 5] % does not work
Matrix OperatorsOperator
Purpose
Matrix operations
+, - Addition, subtraction
.*, ./, .\ Multiply, divide (r. vs. l)
.^ Exponentiation
More matrix operations
C = A*B Matrix Multiply
C = A/B Matrix R. Divide
x = A\b Matrix L. Divide (Solve)
C = A^3 Matrix Power
solves a linear equation systemof the form Ax = b
element-by-element operations
Compatibility Rules:
C4x5 = A4x5 .* B4x5A, B must be same size and shape
Matrix Multiplication Rules: C4x7 = A4x3 * B3x7A.nCols == B.nRowsInner dimensions agree, outer dimensions become new size & shape
An example
Note: Not necessary to compute actualvalues. Simply determine size of the individual factors.
rand(3,4)*[1 2; 3 4; 5 6; 7 8]*ones(2,3)
(3x4) * (4x2) * (2x3)
Results in: (3x3)
Resulting Matrix Sizes of Matrix-value ExpressionsGets trickier if e.g. .* and * are used.Example:
rand(3,4)*[1 2; 3 4; 5 6; 7 8].*ones(3,2)
(3x4) * (4x2) .* (3x2)
(3x2)
(3x2)Evaluates from the left to the right!
Matrix indexingA is a preassigned matrix>>B=A(u,v)B(i,j)=A(u(i),v(j))
What does A(1:2:end,1:2:end) return?
How do you extract the 3x3 matrix around the (4,5) element of A?
Solving Systems of EquationsAx = b
% System of equations5x + 10y – 4z + w = 2
x - 2y + z = 1
2x + 3y + z – 6w = 3
7x + 2z + 3w = 4
% Set up coefficient matrixA = [5 10 -4 1; 1 -2 1 0; ...
2 3 1 -6; 7 0 2 3];
b = [2 1 3 4]; % Setup solution vector
x = A \ b'; % Solve for unknowns
Plotting & Publishing
2D Plotting BasicsTitle
x label
y label
Legend
y axis
x axis
Marker
Plottingplot( x, y, ‘LineSpec’, ‘PropertyName’, ‘PropertyValue’, … );
Plot Attributes line attributes ( ‘-.ro’ )
Line style, Color, Marker other properties
Line Width, Marker Colors
Formatting: xlabel, ylabel, title legend, text, …
More Commands◦axis <min,max>, square, equal
◦ gcf, clf, grid [on|off], …
Multiple plots Overlaying plots
plot( x, [y1 y2…], … ) plot( plot1, plot2,… ) hold on|off
subplot( 3, 2, 3 )
More Plots hist, semilogx, loglog bar, pie, polar, …
Conditional Logic:
Relational OperatorsTests relationship between two objects or arrays
Result is always a logical data type or array of logical data types
Name Operators Examples
Equivalence (binary) Operators
Equality == 5 == 5, x == y
Inequality ~= 5 ~= 5, z == (x^2 + y^2)
Comparison (binary) Operators
Less Than < 5 < 3, sin(2) < cos(y)
Less Than or Equal
<= 4 <= 4,
Greater Than or Equal
>= 7 >= 10
Greater Than > 10 > 7
Logical OperatorsBoolean operatorsName Operators Examples
Unary Operators
Logical Negation (NOT)
~ ~ (3 == 5) = 1 (true)
Binary Operators
Logical And (AND)Short circuit (AND)
& or &&
5 & 7 = 1 (true)
Logical Or (OR)Short circuit (OR)
| or ||
0 | 1 = 1 (true)
Exclusive Or (XOR) XOR xor(8, 5) = 0 (false)
Performs binary logic on two logical data type operands (or arrays) to return a logical result.
Formulating Logical ExpressionMost expressions can be written
directly: E.g. Point is within or on the unit circle◦Condition: x^2+y^2<=1
Sometimes differs from standard math notation◦(2<x)&(x<3) % is correct (Program Style)◦2<x<3 % is incorrect (Math Style)
When in doubt: use parentheses.
if Statements
Single Testif <test> commands; % Section 1end
Test between Two Choicesif <test> commands; % Choice #1 (test was true)else commands; % Choice #2 (test == false)end
if Statements
Chained Tests
if <Test1> commands1; % T1 trueelseif <Test2> commands2; % T1 false T2 %trueelseif <Test3> commands3; % T1, T2 %false, T3 trueelse commands4; % T1,T2,T3falseend
Nested Tests
if <Test1> if <Test2> commands1; % T1,T2 both true else commands2; % T1=1, T2=0 endelse if <Test3> commands3; % T1=0, T3=1 else commands4; % T1,T3 both false endend
Finding Elements/Indexing
Finding Elements/Indexing
Two different ways of finding elementsUsing the find command ind = find( x>3 );
% returns indices of elements in x satisfying test
If you want to extract the respective elements use◦ x( ind ) % returns elements at specified indices
Finding Elements/Indexing
If you want to find the maximum or minimum element in a vector or matrix you can get both the value and indices through min or max.
[minVal, minIndex] = min( x )[maxVal, maxIndex] = max( x )
Functions
Writing Simple functionfunction [o1, o2]=funcName( i1, i2 )% Function Comments… % Body (implementation)end %optional
• Can have multiple inputs (i1) and multiple outputs (o2)
function [] = funcName()function o1 = funcName()function o1 = funcName( i1 )function o1 = funcName( i1, i2 )function [o1, o2] = funcName( i1, i2, i3)
WorkspaceGlobal vs. Local StorageGlobal Workspace
◦Shared by Command Window and script commands
Local Workspace◦Created locally on entry to each
function◦Disappears on exit from function call.
% This is a scriptradius = 10;area = pi .* radius .^2;
function [area] = circ_area(radius)area = pi .* radius .^ 2;
% Call function in workspacemy_area = circ_area( 10 );
Looping
Loops: for loop statementthe counted loop solution
for <varindex> = <start>:<stop><Body: do some work>
end
for <idx> = <start>:<step>:<stop><Body: do some work>
end
Loops: while loop statementthe conditional loop solution
while <test> <Body: do some work> <Update: make progress towards exiting loop>end• While loops are great if we don’t know how many times
we need to loop, but if we can write a test for when we’re done
• For this to work properly, the test needs to evaluate to a logical value
• The while loop will run as long as test evaluates to true
• The while loop does not have a built-in counter like the for-loop (if you want to count something, you need to implement the counter yourself)
Common Idioms: Looping over a matrix• Use a nested for loop:
function ret = findMaxElement( A )sz = size(A);ret = A(1,1);
for i=1:sz(1) for j=1:sz(2) if ( A(i,j)>ret ) ret = A(i,j); end endend