Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration...

16
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    227
  • download

    0

Transcript of Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration...

Lecture 5 ReviewProgrammingProgram Structures

ComparisonRepetition: looping or iterationConditional execution: branching

Bubble Sort

ReviewMatrices – Two dimensional ArraysPlotting – Powerful Matlab commands used to

plot various functions over a specified range.>>plot(x,y) % Plot y as a function of xxlabel(‘axis name’), ylabel(‘yaxis name’),

title(‘Plot Title’)Importing Data

xlsread(‘file name’) % reads the data from an excel spreadsheet and stores them in a two dimensional array

Programming with Script FilesPrograms are contained in script files also known as M-files. A program can be ran by typing its name at the command window.Example: Go to “File” -> “New” -> M-file The Editor window will appear (next slide) Type the following commands:% Program example1 . m% This program computers computes the sine of the square root,% and displays the result .x= sqrt ([3:2 :11]) ;y= sin(x)xlabel (‘x’) ; ylabel (‘f (x)’) ; grid Save as “example1” To run program type >>example1 on the command window NOTE: The m-file location path should be the same as the path

shown in the current directory window.

Programming with Script FilesTo create a new script file:1. Go to the Matlab Desktop

Menu Toolbar.2. File Menu3. New4. M-FileTo open and existing script

file:5. Go to the Matlab Desktop

Menu Toolbar.6. File Menu7. New8. M-FileTo save a script file:9. Go to the Editor Window

Menu Toolbar10. File Menu11. Save As

Matlab code should be typed in the editor window

Programming with Script Files

NOTE: The m-file location path should be the same as the path shown in the current directory window.

Saving an M-file

Setting the Current Directory Path

Program StructuresTo enable the implementation of computer

algorithms, a computer language needs control structures for

ComparisonConditional execution: branchingRepetition: looping or iteration

ComparisonComparison is achieved with relational

operators. The result of a comparison may also be modified by logical operators.

Logical operators are used to combine logical expressions (with “and” or “or”), or to change a logical value with “not”.

Operator Meaning

& And

| Or

~ Not

Example – Logical Operators>> a = 2; b = 4;>> aIsSmaller = a < b;>> bIsSmaller = b < a;>> bothTrue = aIsSmaller & bIsSmallerbothTrue =0>> eitherTrue = aIsSmaller | bIsSmallereitherTrue =1>> ~eitherTrueans =0

Conditional Execution or Branching:As the result of a comparison, or another logical

(true/false) test, selected blocks of program code are executed or skipped.

Conditional execution is implemented with if, if...else, andif...elseif constructs.

There are three types of if constructs1. Plain if2. if...else3. if...elseif

Syntax:if expressionblock of statementsend

Examples1. >>if a < 0, disp(’a is negative’); end2. if x < 0 error(’x is negative; sqrt(x) is imaginary’);

else r = sqrt(x); end3. if x > 0

disp(’x is positive’);elseif x < 0disp(’x is negative’);elsedisp(’x is exactly zero’);end

Repetition or LoopingA sequence of calculations is repeated until

either1. All elements in a vector or matrix have been

processed or2. The calculations have produced a result that

meets a predetermined termination criterionLooping is achieved with for loops and while

loops.Syntax:for index = expressionblock of statementsend

Syntax:while expressionblock of statementsend

For LoopExample: Sum of elements in a vector

x = 1:5; % create a row vectorsumx = 0; % initialize the sumfor k = 1:length(x)sumx = sumx + x(k);end

Example: A loop with an index incremented by twofor k = 1:2:n...end

Example: A loop with an index that counts downfor k = n:-1:1...end

While Loopwhile loops are most often used when an

iteration is repeated until some termination criterion is met.

Example>> while S+ (n+1)^2 < 100n = n+1; S = S + n^2;end>> [n, S]ans =6 91

Bubble SortThe bubble sort works by iterating down an array

to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary.

This process is repeated as many times as necessary, until the array is sorted. Since the worst case scenario is that the array is in reverse order, and that the first element in sorted array is the last element in the starting array, the most exchanges that will be necessary is equal to the length of the array. Here is a simple example:

Bubble Sort Code – For Loop

Assignment 51. Determine how long it will take to

accumulate at least $10,000 in a bank account if you deposit $500 initially and $500 at the end of each year , if the account pays 5 percent annual interest.

2. Use while loops to perform bubble sort.