Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 116: Introduction to Scientific Programming Lecture 36: Final Review I.

Similar presentations


Presentation on theme: "COMP 116: Introduction to Scientific Programming Lecture 36: Final Review I."— Presentation transcript:

1 COMP 116: Introduction to Scientific Programming Lecture 36: Final Review I

2 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

3 Course objectives To 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?

4 Course objectives To 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

5 Course objectives What 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

6 Important points: Operator precedence When in doubt use parentheses Semicolon suppresses output ◦ 5+3; % does not create output ◦ 5+3 % creates output Matlab as a Calculator

7 Super-important: Distinguish between element by element operators and matrix operators. Operators / Full Precedence doc ops PrecedenceOperator 1 (high)Parentheses ( ) * Nesting (inner to outer) 2 Transpose.' or ', Power.^ or ^ 3Unary minus/plus -, + Negation ~ 4Multiplication.* or * Right / Left division./ or /,.\ or \ 5Addition +, Subtraction - 6Colon operator : 7Comparisons = > 8Logical ‘And’ & 9Logical ‘Or’ | 10Logical short-circuit ‘And’ && 11 (low)Logical short-circuit ‘Or’ || * Left to right rule applies Operators Arithmetic: Unary: -, + Binary: +, -, *, /, \, ^.*,./,.\,.^ Assignment: = Colon: : Logical: ~, &, |, &&, ||, XOR Relational: =, >

8 Special Characters CharNameUsage = == Equal Sign :Colon ;Semi-colon ( )Parenthesis [ ]Brackets {}Curly braces.Period 'Apostrophe %Percentage Sign

9 Special Characters CharNameUsage = == Equal Sign1.Assignment 2.Equality test :Colon1. : : ;Semi-colon1. Suppress command output 2. Start a new row in an array ( )Parenthesis1. Force Desired precedence in expressions 2.Indexing Operator 3.Used with function calls [ ]Brackets1.Create Arrays (Vectors & Matrices) 2.Multiple outputs from function calls {}Curly braces1.Construct cell arrays 2.Access cell array content (vs. accessing a sub-cell array with () )..Period1.Decimal point in floating point numbers 2.Access field names in structures 'Apostrophe1.Matrix transpose 2.Construct Character array (string) %Percentage Sign1.Comments (% == grouping comments)

10 Array & Vector Operations

11 Working with Vectors / Matrices Colon Operator ‘:’ v = : v = : : >> 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

12 Important Matrix Functions FunctionExampleNote zeroszeros( 3, 5 ) onesones( 4, 3 ) eyeeye( 4 ) diagdiag( [1 2 3 4] ) randrand(5, 7) sizesize( m ) lengthlength( m ) numelnumel(m) 'm' reshapereshape(m,2,6) repmatrepmat(m,3,2) E = [] deletionE(2:4,:) = []

13 Important Matrix Functions FunctionExampleNote zeroszeros( 3, 5 )Creates m x n matrix of all zeros onesones( 4, 3 )Creates m x n matrix of all ones eyeeye( 4 )Creates n x n Identity matrix diagdiag( [1 2 3 4] )Creates n x n matrix with vector on diag randrand(5, 7)Creates m x n matrix of random values sizesize( m )Returns Vector of size of each dimension lengthlength( m )Returns scalar = maximum dimension size numelnumel(m)Returns total elements in matrix 'm'Transpose matrix (rows ↔ columns) reshapereshape(m,2,6)Reshapes matrix to new r x c layout repmatrepmat(m,3,2)Builds large matrix from r x c copies of specified small matrix, IE ‘m’ E = []create an empty matrix or vector variable deletionE(2:4,:) = []Delete 2 nd thru 4 th rows from array

14 Concatenation Vectors 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

15 Matrix Operators OperatorPurpose 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 system of the form Ax = b element-by-element operations Compatibility Rules: C 4x5 = A 4x5.* B 4x5 A, B must be same size and shape Matrix Multiplication Rules: C 4x7 = A 4x3 * B 3x7 A.nCols == B.nRows Inner dimensions agree, outer dimensions become new size & shape

16 An example Note: Not necessary to compute actual values. 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)

17 Resulting Matrix Sizes of Matrix-value Expressions Gets 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) Evaluates from the left to the right!

18 Matrix indexing A 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?

19 Solving Systems of Equations Ax = b % System of equations 5x + 10y – 4z + w = 2 x - 2y + z = 1 2x + 3y + z – 6w = 3 7x + 2z + 3w = 4 % Set up coefficient matrix A = [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

20 Plotting & Publishing

21 2D Plotting Basics Title x label y label Legend y axis x axis Marker

22 Plotting plot( 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, 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, …

23 Conditional Logic:

24 Relational Operators Tests relationship between two objects or arrays Result is always a logical data type or array of logical data types NameOperatorsExamples 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

25 Logical Operators Boolean operators NameOperatorsExamples 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)XORxor(8, 5) = 0 (false) Performs binary logic on two logical data type operands (or arrays) to return a logical result.

26 Formulating Logical Expression Most 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.

27 if Statements Single Test if commands; % Section 1 end Test between Two Choices if commands; % Choice #1 (test was true) else commands; % Choice #2 (test == false) end

28 if Statements Chained Tests if commands1; % T1 true elseif commands2; % T1 false T2 %true elseif commands3; % T1, T2 %false, T3 true else commands4; % T1,T2,T3false end Nested Tests if commands1; % T1,T2 both true else commands2; % T1=1, T2=0 end else if commands3; % T1=0, T3=1 else commands4; % T1,T3 both false end

29 Finding Elements/Indexing

30 Two different ways of finding elements Using 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

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

32 Functions

33 Writing Simple function function [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)

34 Workspace Global vs. Local Storage Global 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 script radius = 10; area = pi.* radius.^2; function [area] = circ_area(radius) area = pi.* radius.^ 2; % Call function in workspace my_area = circ_area( 10 );

35 Looping

36 Loops: for loop statement the counted loop solution for = : end for = : : end

37 Loops: while loop statement the conditional loop solution while 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)

38 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


Download ppt "COMP 116: Introduction to Scientific Programming Lecture 36: Final Review I."

Similar presentations


Ads by Google