Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be...

24
Lecture 32

Transcript of Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be...

Page 1: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Lecture 32

Page 2: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Chapter 4 "Inheritance"Inheritance is a powerful feature that allows the reuse of code.However, be sure that functions applied to objects created at

run time through the new operator are bound at run time. This feature is known as dynamic binding, and the use of virtual functions is required to ensure that run-time decisions are made.

Reread this chapter as often as necessary to ensure that you understand the distinctions among non-virtual functions virtual functions pure virtual functions

Page 3: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Chapter 6 “Algorithm Analysis"In this chapter we introduced algorithm analysis and showed that

algorithmic decisions generally influence the running time of a program much more than programming tricks do

We also showed the huge difference between the running times for quadratic and linear programs and illustrated that cubic algorithms are, for the most part, unsatisfactory

We examined an algorithm that could be viewed as the basis for our first data structure

The binary search efficiently supports static operations thereby providing a logarithmic worst-case search

Later in the text we examine dynamic data structures that efficiently support updates

Page 4: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Data Visualization with MATLABChapter 2 “MATLAB Environment”Chapter 3 “Built-in MATLAB Functions”Chapter 5 “Plotting”Chapter 6 “User-Defined Functions”Chapter 13 “Numerical Techniques”

Page 5: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Chapter 2 "MATLAB Environment"In this chapter, we introduced the basic MATLAB structureThe MATLAB environment includes multiple windows, four of

which are open in the default view:Command windowCommand history windowWorkspace windowCurrent folder window

In addition, theDocument windowGraphics windowEdit window

open as needed during a MATLAB session

Page 6: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….Variables defined in MATLAB follow common computer naming

conventions:Names must start with a letter.Letters, numbers, and the underscore are the only characters allowed.Names are case sensitive.Names may be of any length, although only the first 63 characters are used

by MATLAB Some keywords are reserved by MATLAB and cannot be used as variable

namesMATLAB allows the user to reassign function names as variable names,

although doing so is not good practice.The basic computational unit in MATLAB is the matrix. Matrices may be

Scalars ( 1 x 1 matrix)Vectors ( 1 x n or n x 1 matrix, either a row or a column)Two-dimensional arrays ( m x n or n x m )Multidimensional arrays

Page 7: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued…. Matrices often store numeric information, although they can store other kinds of

information as well Data can be entered into a matrix manually or can be retrieved from stored data files When entered manually, a matrix is enclosed in square brackets, elements in a row are

separated by either commas or spaces, and a new row is indicated by a semicolon:

a = [1 2 3 4; 5 6 7 8] Evenly spaced matrices can be generated with the colon operator. Thus, the command

b = 0:2:10

creates a matrix starting at 0, ending at 10, and with an increment of 2 The linspace and logspace functions can be used to generate a matrix of specified length

from given starting and ending values, spaced either linearly or logarithmically The help function or the MATLAB Help menu can be used to determine the appropriate

syntax for these and other functions

Page 8: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….MATLAB follows the standard algebraic order of operationsMATLAB supports both standard (decimal) and scientific notationIt also supports a number of different display options. No matter how values

are displayed, they are stored as double-precision floating-point numbersMATLAB variables can be saved or imported from either .MAT or .DAT

filesThe .MAT format is proprietary to MATLAB and is used because it stores

data more efficiently than other file formatsThe .DAT format employs the standard ASCII format and is used when data

created in MATLAB will be shared with other programsCollections of MATLAB commands can be saved in script M-files. This is

the best way to save the list of commands used to solve a problem so that they can be reused at a later time

Cell mode allows the programmer to group M-file code into sections and to run each section individually. It is especially convenient when one M-file is used to solve multiple problems.

Page 9: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Chapter 3 “Built-in MATLAB Functions"General mathematical functions, such as

exponential functionslogarithmic functionsroots

Rounding functionsFunctions used in discrete mathematics, such as

factoring functionsprime-number functions

Trigonometric functions, includingstandard trigonometric functionsinverse trigonometric functionshyperbolic trigonometric functionstrigonometric functions that use degrees instead of radians

Page 10: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….Data analysis functions, such as

maxima and minimaaverages (mean and median)sums and productssortingstandard deviation and variance

Random-number generation for bothuniform distributionsGaussian (normal) distributions

Functions used with complex numbers

Page 11: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Chapter 5 “Plotting"The most commonly used graph in engineering is the x – y plotThis two-dimensional plot can be used to graph data or to visualize

mathematical functionsNo matter what a graph represents, it should always include a title and x -

and y -axis labelsAxis labels should be descriptive and should include units, such as ft/s or

kJ/kg MATLAB includes extensive options for controlling the appearance of your plots

The user can specify the color, line style, and marker style for each line on a graph

A grid can be added to the graph, and the axis range can be adjustedText boxes and a legend can be employed to describe the graphThe subplot function is used to divide the plot window into an mxn gridInside each of these subwindows, any of the MATLAB plots can be

created and modified

Page 12: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….In addition to x – y plots, MATLAB offers a variety of plotting options,

including polar plots, pie charts, bar graphs, histograms, and x – y graphs with two y –axes

The scaling on x – y plots can be modified to produce logarithmic plots on either or both x – and y- axes

Engineers often use logarithmic scaling to represent data as a straight line

The function fplot allows the user to plot a function without defining a vector of x - and y –values

MATLAB automatically chooses the appropriate number of points and spacing to produce a smooth graph

Additional function-plotting capability is available in the symbolic toolbox

Page 13: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….The three-dimensional plotting options in MATLAB include a line plot, a

number of surface plots, and contour plotsMost of the options available in two dimensional plotting also apply to these

three-dimensional plotsThe meshgrid function is especially useful in creating three-dimensional

surface plotsInteractive tools allow the user to modify existing plotsThese tools are available from the figure menu barPlots can also be created with the interactive plotting option from the

workspace windowThe interactive environment is a rich resourceFigures created in MATLAB can be saved in a variety of ways, either to be

edited later or to be inserted into other documentsMATLAB offers both proprietary file formats that minimize the storage

space required to store figures and standard fi le formats suitable to import into other applications

Page 14: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Chapter 6 “User Defined Functions"MATLAB contains a wide variety of built-in functionsHowever, you will often find it useful to create your own

MATLAB functionsThe most common type of user-defined MATLAB function is

the function M-file, which must start with a function-definition line that containsthe word function a variable that defines the function outputa function namea variable used for the input argumentFor example,

function output = my_function(x)

Page 15: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….The function name must also be the name of the M-file in which the

function is storedFunction names follow the standard MATLAB naming rulesLike the built-in functions, user-defined functions can accept

multiple inputs and can return multiple resultsComments immediately following the function-definition line can

be accessed from the command window with the help commandVariables defined within a function are local to that function. They

are not stored in the workspace and cannot be accessed from the command window

Global variables can be defined with the global command used in both the command window and a MATLAB function. Good programming style suggests that define global variables with capital letters. In general, however, it is not wise to use global variables

Page 16: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….Groups of user-defined functions, called “toolboxes,” may be stored in a

common directory and accessed by modifying the MATLAB® search path. This is accomplished interactively with the path tool, either from the menu bar, as in

File -> Set Path

or from the command line, with pathtoolMATLAB provides access to numerous toolboxes developed at The

MathWorks or by the user communityAnother type of function is the anonymous function, which is defined in a

MATLAB session or in a script M-file and exists only during that sessionAnonymous functions are especially useful for very simple mathematical

expressions or as input to the more complicated function functions

Page 17: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Chapter 13 “Numerical Techniques"Tables of data are useful for summarizing technical informationHowever, if a value is needed that is not included in the table,

must approximate that value by using some sort of interpolation technique

MATLAB includes such a technique, called interp1 . This function requires three inputs: a set of x -values, a corresponding set of y -values, and a set of x -values for which you would like to estimate y -values

The function defaults to a linear interpolation technique, which assumes that approximate these intermediate y -values as a linear function of x that is,

y = f(x) = ax + b

Page 18: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….A different linear function is found for each set of two

data points, ensuring that the line approximating the data always passes through the tabulated points

The interp1 function can also model the data by using higher-order approximations, the most common of which is the cubic spline

The approximation technique is specified as a character string in a fourth optional field of the interp1 function

If it’s not specified, the function defaults to linear interpolation. An example of the syntax is

new_y = interp1(tabulated_x, tabulated_y, new_x, 'spline')

Page 19: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….In addition to the interp1 function, MATLAB includes a two-

dimensional interpolation function called interp2 , a three-dimensional interpolation function called interp3 , and a multidimensional interpolation function called interpn

Curve-fitting routines are similar to interpolation techniquesHowever, instead of connecting data points, they look for an equation

that models the data as accurately as possibleOnce you have an equation, you can calculate the corresponding

values of y The curve that is modeled does not necessarily pass through the

measured data pointsMATLAB’s curve-fitting function is called polyfit and models the

data as a polynomial by means of a least-squares regression technique

Page 20: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….The function returns the coefficients of the polynomial equation of the

form

These coefficients can be used to create the appropriate expression in MATLAB, or they can be used as the input to the polyval function to calculate values of y at any value of x

For example: the following statements find the coefficients of a second-order polynomial to fi t the input x–y data and then calculate new values of y , using the polynomial determined in the first statement:coef = polyfit(x,y,2)y_first_order_fit = polyval(coef,x)

These two lines of code could be shortened to one line by nesting functions:y_first_order_fit = polyval(polyfit(x,y,1),x)

Page 21: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….MATLAB also includes an interactive curve-fitting capability that allows the user to

model data not only with polynomials, but with more complicated mathematical functions

The basic curve-fitting tools can be accessed from the Tools menu in the figure window

More extensive tools are available in the curve-fitting toolbox, which is accessed by typing cftool

in the command window.Numerical techniques are used widely in engineering to approximate both derivatives

and integralsDerivatives and integrals can also be found with the symbolic toolboxThe MATLAB diff function finds the difference between values in adjacent elements

of a vectorBy using the diff function with vectors of x - and y -values, we can approximate the

derivative with the command slope = diff(y)./diff(x)

The more closely spaced the x and y data are, the closer will be the approximation of the derivative

Page 22: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….The gradient function uses a forward difference approach to

approximate the derivative at the first point in an arrayIt uses a backward difference approach for the final value in the array,

and a central difference approach for the remainder of the pointsIn general, the central difference approach gives a more accurate

approximation of the derivative than either of the other two techniques

Integration of ordered pairs of data is accomplished using the trapezoidal rule, with the trapz function

This approach can also be used with functions, by creating a set of ordered pairs based on a set of x values and the corresponding y values

Page 23: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued…. Integration of functions is accomplished more directly with one of two quadrature

functions: quad or quadl These functions require the user to input both a function and its limits of

integrationThe function can be represented as a character string, such as

'x.^2-1‘

as an anonymous function, such as my_function = @(x) x.^2-1

or as an M-fi le function, such as function output = my_m_file(x) output = x.^2-1;

Any of the three techniques for defining the function can be used as input, along with the integration limits—for example, quad('x.^2-1',1,2)

Both quad and quadl attempt to return an answer accurate to within The quad and quadl functions differ only in the technique they use to estimate the

integralThe quad function uses an adaptive Simpson quadrature technique, and the quadl

function uses an adaptive Lobatto quadrature technique

Page 24: Chapter 4 "Inheritance" Inheritance is a powerful feature that allows the reuse of code. However, be sure that functions applied to objects created at.

Continued….MATLAB includes a series of solver functions for first-order

ordinary differential equations and systems of equationsAll of the solver functions use the common format

[t,y] = odesolver(function_handle,[initial_time, final_time],

[initial_cond_array])A good first try is usually the ode45 solver function, which uses

a Runge–Kutta techniqueOther solver functions have been formulated for stiff differential

equations and implicit formulationsThe ode solver functions require that the user know the initial

conditions for the problemIf, instead, boundary conditions are known at other than the

starting conditions, the bvp4 function should be used