1 / 38

COMP 116: Introduction to Scientific Programming

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.

ura
Download Presentation

COMP 116: Introduction to Scientific Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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. Matlab as a Calculator Important points: • Operator precedence • When in doubt use parentheses • Semicolon suppresses output • 5+3; % does not create output • 5+3 % creates output

  7. Operators / Full Precedencedoc ops Super-important: Distinguish between element by element operators and matrix operators.

  8. Special Characters

  9. Special Characters

  10. Array & Vector Operations

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

  12. Important Matrix Functions

  13. Important Matrix Functions

  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 element-by-element operations Compatibility Rules: C4x5 = A4x5 .* B4x5 A, B must be same size and shape solves a linear equation system of the form Ax = b Matrix Multiplication Rules: C4x7 = A4x3 * B3x7 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) (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 EquationsAx = 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 y axis Legend y label Marker x axis x label

  22. 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, …

  23. Conditional Logic:

  24. Relational OperatorsTests relationship between two objects or arrays • Result is always a logical data type or array of logical data types

  25. Logical OperatorsBoolean operators • 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 <test> commands; % Section 1 end Test between Two Choices if <test> commands; % Choice #1 (test was true) else commands; % Choice #2 (test == false) end

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

  29. Finding Elements/Indexing

  30. Finding Elements/Indexing 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. WorkspaceGlobal 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 statementthe counted loop solution for <varindex> = <start>:<stop> <Body: do some work> end for <idx> = <start>:<step>:<stop> <Body: do some work> end

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

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

More Related