CEE15ClassNotes PDF
CEE15ClassNotes PDF
CEE15ClassNotes PDF
Arun Prakash
School of Civil Engineering Purdue University.
Contents
1 Introduction to Computing
1.1 1.2 1.3 2.1 Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Computer Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Basic Matrix Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Legends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
4 5 7
2.2 2.3
2.4
8 8 9 10 11 12 13 13 14 15 15 15 17 18 18 18 20 21 22 23
3 Branching Statements
3.1
3.2
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
24
24 25 25 26 27 29 30
The swith statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Top-Down Design Techniques . . . . . . . . . . . Loops . . . . . . . . . . . . . . . . . . . . . . . . The for Loop . . . . . . . . . . . . . . . . . . . . 4.3.1 The general form of the for Loop . . . . . The while Loop . . . . . . . . . . . . . . . . . . . Simple Applications . . . . . . . . . . . . . . . . . Timing, Preallocation and Vectorization of Loops The rek and ontinue Statements . . . . . . . Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
31 32
4 Loops
33
33 35 36 36 38 39 41 42 43
5.2
Additional Types of Two-dimensional Plots . . . . 5.1.1 Other Useful Plotting Functions . . . . . . 5.1.2 Logarithmic Plots . . . . . . . . . . . . . . 5.1.3 Subplots . . . . . . . . . . . . . . . . . . . 5.1.4 Creating Multiple Figure Windows . . . . 5.1.5 Exporting a Plot as a Graphical Image . . Three-dimensional Plots . . . . . . . . . . . . . . 5.2.1 plotQ function . . . . . . . . . . . . . . . 5.2.2 The meshgrid, mesh and surf commands 5.2.3 The Contour functions . . . . . . . . . . . 5.2.4 Generating Animations of Plots . . . . . .
45
46 46 47 47 48 49 50 50 51 52 53 54 59 60 60 61
Introduction to Matlab Functions . . . . . . . . . . . . Variable Passing in Matlab: The Pass-by-Value Scheme Optional Arguments . . . . . . . . . . . . . . . . . . . Function of functions . . . . . . . . . . . . . . . . . . . Recursive Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
54
The textred@A Function . . . . . . . . . Introduction to MATLAB File Processing File Opening and Closing . . . . . . . . . 7.3.1 The fopen Function . . . . . . . . 7.3.2 The flose Function . . . . . . . . File Positioning and Status Functions . . . I/O Functions for Formatted Text Data . . 7.5.1 The fprintf Function . . . . . . . 7.5.2 The fsnf Function . . . . . . . . 7.5.3 The fgetl and fgets Functions . .
64
64 65 65 65 67 68 69 69 70 70
7.6
I/O Functions for Binary Data . . . . . . . . . . . . . . . . . . . . . . . . . . 7.6.1 The fwrite Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.6.2 The fred Function . . . . . . . . . . . . . . . . . . . . . . . . . . . Matrix Algebra . . . . . . . . Data Analysis . . . . . . . . . Polynomials . . . . . . . . . . 8.3.1 Roots . . . . . . . . . 8.3.2 Curve Fitting . . . . . Integration . . . . . . . . . . . Dierential Equations . . . . . 8.5.1 IVP Format . . . . . . 8.5.2 ODE Solvers . . . . . . 8.5.3 Basic Use . . . . . . . Advanced MATLAB Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
71 71 72
73
8.6
73 74 76 76 76 78 78 78 79 79 84
85
1.1 Computing
Why do we need Computing?
Volume of data and societal needs have grown beyond human capabilities Human error, consistency of results, speed and accuracy Examples: Banking, Automotive, Manufacturing, Communication etc. Questions: Reliability, Fault tolerance, robustness, backup Caveat: Utilization vs. Dependence; we are responsible for the technology we create and use.
Types of Computing
On-site Data Analysis and response systems in real-life applications: Structural Health Monitoring and Control Water quality management Earthquake Engineering Direct simulation of physical phenomena (Scientic Computing) Analysis & design of systems such as buildings, bridges, machines etc. Verify & Validate current and future theories of physics - Simulate stu we cannot measure or observe - subatomic particles, core of stars, even origin of the universe!!
4
Components of a computer
Hardware CPU - Binary (0,1) instructions go in ; Binary output obtained Memory - ROM, RAM, Hard Disk, External Storage Input Devices - Keyboard, Mouse, Touch Screen etc. Output Devices - Monitor, Printer etc. Software
Operating system
Windows, MacOS, Linux, Unix, Sun Solaris, Internet Explorer, Media Players, Photoshop, Adobe Acrobat Programming languages: C/C++, Fortran, Pascal etc. MATLAB Your programs
Applications Programs
Dening the set of operations for a computer to perform (telling the computer what to do). Computers understand only certain binary instructions. So computer scientists developed more user friendly languages that translated (compiled / interpreted) into binary code. We need to learn these languages in order to communicate with the computers by writing programs.
Structure of a program:
Get input Compute - operate upon the input data to generate meaningful information Output the results
Some Essentials of Programming
Data Structure for Memory management - Variables, Array, Pointers Conditional Branching Statements Loops File Handling Input / Output Graphics
Advantages:
Relatively easy to use and good for beginners, GUI Predened functions for a lot of Mathematical operations: Matrix Algebra, Solving system of equations, Eigenvalue computations Symbolic Mathematics: Algebra, Dierentiation, Integration Additional Toolboxes Plotting / Imaging / Visualization of Results - device independent Combine Languages, C/C++, Fortran Dierent platforms run the same MATLAB program / code Demos : Membrane, 3D peaks, Bar with notch
Disadvantages:
Interpreter based : Slower, but can be compiled Kernel overhead - not suitable for very large problems Limited advanced programming features: Pointers, Pass by Reference, Object-oriented
The MATLAB Environment
Desktop Command window bb is called the 'command prompt' Arithmetic: CD ED BD GD Line continuation (Ellipsis) FFF Command History window Workspace browser: Variables whosD lerD lD lf Path Browser - Variable, m-le in current directory, rst occurrence whih Editor window : m-les as scripts Figure windows plot
Help helpD lookfor Getting started section Start Button Other commands CTRL-c : Cancel or Interrupt Operation (when MATLAB 'hangs') ! : execute command on MS-DOS or Unix shell prompt diry
Built-in functions in MATLAB
Trigonometric functions
; ; ; ;
Hyberbolic functions
sinh( ) tanh( )
; ;
cosh( ) coth( )
A Variable is user given name that refers to a certain location in the computers memory where MATLAB stores data. The user can access that data by specifying the variable name associated with it.
Rules:
1. Variable names are case sensitive. Example: vrD rD e are all dierent. 2. Must begin with an alphabet followed by alphabets, numbers and the underscore _ character. 3. MATLAB can distinguish variable names upto 63 characters in length.
Examples
x a IH x a x C I a PH C PHi hrterI a 99 hrterP a 9I9 ghrrI a hr@WUA trrI a 9his is gii IS9 stringvrile a 9hts ool39
Note: Choose the names of your variables so that no inbuilt predened variables or functions
Arrays
MATLAB treats all data as arrays. An array is a `collection of data' (any data - numbers, characters etc.) that is stored in continuous locations in the computers memory. All variables refer to arrays in the computers memory. Even scalars are actually treated as 1 1 array. Arrays are primarily of two types: Vectors (dimension 1) and Matrices (2 or more dimensions). The size of an array is the number of rows and columns in an array. (For higher dimensional arrays it includes the extent of all dimensions).
Example:
1 2 a = 3 4 5 6 b= 1 2 3 4 1 c = 2 3
COMMANDS: length@AD size@A size@A gives the size of a specic matrix . length@A returns the length of a vector or the longest dimension of a 2-D array.
Individual elements in an array are accessed using the row and column number of the element in parentheses. For example, in the above arrays @PDIA is 3, @PA is 2, and @QA is 3.
2.1.3 Initialization of Variables and Arrays
Variables need not be declared prior to using them (unlike C, C++, Fortran etc.). Variables can be created and stored using: 1. Assignment
vr a expression re a piB@PFQAP myrryI a I P Q Y R S T myrryI@QDPA a I (expanding an existing array) Note If a particular subscript in not in range of an array, MATLAB automatically increases the dimensions of the array to t the new element. vr a first X in X lst (default in is 1) myrryP a IXS creates a row vector myrryQ a IXSXPT Y PSXSXSH Note: Number of entries in each row must be equal. olI a IXQ9 olP a TXEIXR9 myrryR a olI olP myrryR a myrryR olP olI nme a 9wike9 9 9 9mith9 mgi@ AD zeros@ AD ones@ AD eye@ A
2. Shortcut Expressions
3. Combining arrays
4. Built-in Functions
from 1 through n2 . The integers are ordered in such a way that all the row sums and all the column sums are equal to the same number. zeros: The zeros function generates a matrix containing all zeros. ones: The ones function generates a matrix containing all ones. eye: The eye function generates an identity matrix.
magic: The mgi@nA function generates an n n matrix constructed from the integers
10
Used in short-cut expressions Assignment operator Subscripts of arrays Brackets; forms arrays Separates array elements Semicolon; suppresses echo of input, ends row in array Single quote; matrix transpose, creates string
2.1.4
Multi-dimensional Arrays
Three dimensional arrays can be visualized as cuboids and can be addressed using 3 subscripts. For example
rryRd@PDPDPDPA a I is a 2 2 2 2 array.
However higher dimension arrays are harder to visualize and should be thought of in terms of subscripts. For example
11
2.1.5
Subarrays
It is possible to select and use subsets of MATLAB arrays as though they were separate arrays. To select a portion of an array, just include a list of all the elements to be selected in the parentheses after the array name. For example,
rrI a IFI EPFP QFQ ERFR SFS; rrI@QA QFQ rrI@I RA IFI ERFR rrI@IXPXSA IFI QFQ SFS
For a two-dimensional array, a colon can be used in a subscript to select all of the values of that subscript. For example,
rrP@PXendDXA
EP EQ ERY Q R S
Subarrays can also be used to change the values of that portion of the main array. For example,
12
MATLAB has all the operators of conventional matrix algebra already built in.
Addition and Subtraction of Matrices is carried out on two or more matrices of the Transpose of a Matrix The transpose of a matrix is a new matrix in which the rows of
the original matrix are the columns of the new matrix. If a matrix contains a complex value then we can have both the complex conjugate transpose (trnspose and 9) and complex nonconjugate transpose (trnspose and F9).
a dot@DA The dot product is the scalar computed from two vectors of the same size.
n
c=
i=1
ai b i
a B
c=ab
cij =
k=1
aik bkj
For example if matrices and of dimensions m n and n p respectively are such that number of columns of are equal to number of rows in (in this case: n) then the resulting matrix will have dimensions m p according the above formula. to 2). P is equivalent to B. Similarly, R is equivalent to BBB. To raise a matrix to a power, the matrix must be a square matrix.
Matrix Powers The command for the power of a matrix is P (where, power is equal
Matrix Inverse MATLAB Command: a inv@A By denition, if is an inverse of a square matrix , then B or B are both equal to an identity matrix with only the diagonal elements being 1 and other elements being 0. Determinants MATLAB Command: Solving system of equations
det@A
The solution of a system of equations A x = b is given by x = A1 b. The direct way of calculating this solution using x a inv@eAB is expensive. Alternatively, MATLAB can solve this system using Gaussian elimination which is implemented as the backslash \ . MATLAB Command: x a e \ .
13
2.2.2
Array operations
a I P Q Y R S T a R S T Y I P Q FB denotes element-by-element multiplication of and . A normal matrix multiplication between the above matrices is not dened.
Sometimes we have to perform arithmetic operations between the elements of two arrays of the same size in an element-by-element manner. These operators are denoted by preceding the normal arithmetic operators by a dot . such as (FCD FED FBD FGD F) . For example if and are matrices of same size:
Note + & .+
- & .-
Summary of Array and Matrix operators Character Description C or E Array and Matrix addition or subtraction of arrays
FB FG F\ F B G \
Element-by-element multiplication of arrays Element-by-element right division : a/b = @iDjAG@iDjA Element-by-element left division : a\b = @iDjAG@iDjA Element-by-element exponentiation Matrix multiplication Matrix right divide : G a B@A1 Matrix left divide (equation solve) : \ a @A1 B Matrix exponentiation
14
We can ask the user to provide input data using the input@A command.
9A
This allows the user to enter any valid MATLAB expression, that evaluates to a numeric or character value.
2.3.2
(Default) Fixed-point format with 4 decimal digits Scientic notation with 4 decimal digits Best of 5-digit xed or oating point Fixed-point format with 14 decimal digits Scientic notation with 15 decimal digits Best of 15-digit xed or oating point Two decimal digits Eliminates empty lines Adds empty lines Only signs are printed
15
7 7s \n
Display value as an integer Display value in exponential format Display value in oating point format Display value in either oating point or exponential format, whichever is shorter Display a single character Display a string of characters Skip to a new line
Example
\n9DtempA
will print: he temperture is UVFPQRT degreesF It is also possible to specify the width of the eld in which a number will be displayed and the number of decimal places to display. This is done by specifying the width and precision after the 7 sign and before the f. For example,
\n9DtempA
will print: he temperture is UVFP degreesF The output contains the value of temp printed with 4 positions, one of which will be a decimal position as shown above.
2.3.3
Matrices can be dened from information that has been stored in a data le. MATLAB can interface to two dierent types of data les.
MAT les: Data stored in a memory-ecient binary format. They are preferable for data that are going to be generated and used by MATLAB programs only. ASCII les: Data stored in ASCII characters. They are necessary if the data are to be shared (imported or exported) with programs other than MATLAB.
MAT Files
sve filenme vrI vrP vrQ The sve command saves the values of variables vrID vrPD etc. in a le named filenme. By default, the le name will be give the extent mt, and such data les are called MAT-les. sve filenme x y z Eppend adds the variables xD yD z to an existing MAT le filenmeFmt.
The load command is the opposite of the save command. It loads data from a disk le into the current MATLAB workspace. For example,
lod filenme
ASCII Files
The ASCII les must contain only numeric information. We can use % in the ASCII le for comment lines. Each row of the ASCII le must contain the same number of data values to be read by another program in MATLAB.
lod tempFdt
17
plot
command
The plot@A command generates an x-y plot using 2 arrays. For example to plot the function y = x2 10x + 15 for values of x between 0 and 8.
Figure 2.1: Plot of y = x2 8x + 15 from 0 to 8. The rst statement creates a vector of x values between 0 and 10 using the colon operator. The second statement calculates the y values from the equation. Finally, the third statement creates the plot using plot function. When the plot function is executed, Matlab opens a Figure Window and displays the plot in the window, see Figure 2.1. Note: Both vectors of x and y must have the same length.
2.4.2 Title, Label, Grid and Text
Titles and axis labels can be added to a plot with the title, xlel, and ylel functions. Each function is called with a string containing the title or label to be applied to 18
the plot. Grid lines can be added or removed from the plot with the grid command: grid on turns on the grid lines, and grid off turns o grid lines. For example, titles, labels and grid lines are applied to the previous gure, as shown in Figure 2.2.
x a HXIXVY y a xFP E VFBx C ISY plot@xDyAY title@9lot of y a xP E VBx C IS9AY xlel@9x9AY ylel@9y9AY grid onY
Figure 2.2: Plot of y = x2 8x + 15 from 0 to 8 with a title, axis labels, and grid lines. The function, text@xDyD9string9A writes the string on the graphics screen at the points specied by the coordinates (xDy) using the axes from the current plot. If x and y are vectors then the text is written in each point.
19
2.4.3
It is possible to plot multiple curves on the same graph. We can plot multiple curves on the same graph by using multiple arguments in the plot command, for example, plot@xIDyIDxPDyPA. Here, xI, yI, xP and yP are vectors. When the command is executed, the curve corresponding to xI and yI will be plotted, and then the curve corresponding to xP and yP will be plotted on the same graph. Another way to plot multiple curves on the same graph is with the hold command. After a hold on command is issued, all additional plots will be laid on top of the previously existing plots. A hold off command switches plotting behavior back to the default situation, in which a new plot replaces the previous one. For example, suppose that we want to plot the function f (x) = sin2x and its derivative, 2cos2x, on the same plot. We can use either of the following two ways (the result is shown in Figure 2.3):
or
Figure 2.3: Plot of f (x) = sin2x and f (x) = 2cos2x on the same graph.
20
2.4.4
Matlab allows to select the color of a line to be plotted, the style of the line to be plotted, and the type of marker to be used for data points on the line. These traits may be selected using an attribute character string after the x and y vectors in the plot function. The attribute character string can have up to three characters, with the rst character specifying the color of the line, the second character specifying the style of the marker, and the last character specifying the style of the line. The characters for various colors, markers, and line styles are shown in the following table:
Table of Plot Colors, Marker Styles, and Line Styles Color Marker Style Line Style
y m r g w k
yellow magenta cyan red green blue white black
F o x C B s d v ` b p h `noneb
point circle x-mark plus star square diamond triangle (down) triangle (up) triangle (left) triangle (right) pentagram hexagram no marker
E X EF EE `noneb
The attribute characters may be mixed in any combination, and more than one attribute string may be specied if more than one pair of (x, y ) vectors are included in a single plot function.
It is also possible to set additional properties associated with lines and markers in the gure.
vineidth species the width of each line in points. wrkeridgegolor species the color of the marker or the edge color for lled markers. wrkerpegolor species the color of the face of lled markers. wrkerize species the size of the marker in points.
These properties are specied in the plot command after the data to be plotted in the following fashion:
21
Adding Legends
Legends may be created with the legend function. The basic form is
legend@9stringI9D 9stringP9D FFFD 9votion9D posA or legend@9stringI9D 9stringP9D FFFA where stringI, stringP, etc. are the labels associated with the lines plotted, and pos may be a string specifying where to place the legend. Command legend off will remove an existing legend. The possible values of position are given in the following table.
2.4.5
By default, a plot is displayed with x- and y -axis ranges wide enough to show every point in an input data set. However, we can use the xis command/function to control axis scaling and appearance. Some of the forms of the xis command/function are: 1. v a xisY returns a 4-element row vector containing the current limits, xminD xmxD ymin, and ymx, of the plot. 2. xis@xmin xmx ymin ymxA sets the x and y limits of the plot to the specied values. 3. xis equl sets the axis increments to be equal on both axes. 4. xis squre makes the current axis box square. 5. xis norml cancels the eect of axis equal and axis square. 6. xis off turns o all axis labelling, tick marks, and background. 7. xis on turns on all axis labelling, tick marks, and background (default case). An example of a complete plot is shown in Figure 2.4, and the statements to produce that plot are shown below.
22
x a HXpiGPSXPBpiY yI a sin@PBxAY yP a PBos@PBxAY plot@xD yID 9goE9D 9wrkerize9D TFHD 9wrkeridgegolor9D 99D 9wrkerpegolor9D 9g9AY hold onY plot@xD yPD 9rdE9D 9wrkerize9D TFHD 9wrkeridgegolor9D 9r9D 9wrkerpegolor9D 9g9AY title@9lot of f@xA a sin@PxA nd its derivtive9AY xlel@9x9AY ylel@9y9AY legend@9f@xA9D 9dGdx f@xA9D 9votion9D 9xorthest9AY
Figure 2.4: A complete plot with title, axis labels, legend, grid, and multiple line styles.
2.4.6
You can perform similar operations to control the settings of a plot using GUI Plotting Tools. However, this process has to be done manually and is not recommended when dealing with a large of plots. Refer to MATLAB help for details on plotting tools.
23
3.1 Branching
Branches are used to make decisions in your program and to run dierent pieces of code depending upon some logical condition that can be either true or false . For example: . . .
if
If the logical condition is true, then the program executes the statements A, otherwise, the program executes the statements B. After the if-construct the program goes to the line immediately following end. The value of these logical conditions is stored in a dierent MATLAB datatype called the logical datatype.
24
3.1.1
The logil data type can have one of only two possible values: true or flse. These values are produced by the two special functions true and flse. They are also produced by two types of MATLAB operators: relational operators and logical operators. To create a logil variable, just assign a logical value to it in an assignment statement. For example, the following statement creates a logical variable lI containing the logical value true.
lI a trueY
In MATLAB, numerical and logical data can be mixed in expressions. If a logical value is used in a place where a numerical value is expected, true values are converted to 1 and flse values are converted to 0, and then used as numbers. If a numerical value is used in a place where a logical value is expected, non-zero values are converted to true and zero values are converted to flse, and then used as logical values. The inbuilt function logil@A does this conversion explicitly. For example logil@HA is flse and logil@xA, where x is some non-zero number, gives true.
3.1.2 Relational Operators
logil result, depending on the relationship between the two operands. The general form of a relational operator is I `opb P
Relational Operators are operators with two numerical or string operands that yield a
where I and P are arithmetic expressions, variables, or strings, and `opb is one of the following relational operators:
Note:
Relational operators may be used to compare a scalar value with an array. logrrI a rryI ` Q Relational operators may be used to compare two arrays if they have the same size. logrrP a rryI b rryP
25
Relational operators may be used to compare two strings if they are of equal lengths. logrrQ a 9his is string I9 aa 9his is sxq P9 The aa symbol is a comparison operation that returns a logical result, while the a symbol is an assignment operation that assigns the value of the expression on the right of the equal sign to the variable on the left of the equal sign. Due to roundo errors during computer calculation, two theoretically equal numbers can dier slightly. For example,
a HY a sin@piAY a @ aa AY
The logical variable should have the value of true, while the result of MATLAB is flse. Because the result of sin@piA MATLAB calculated is 1.2246 1016 instead of exactly zero. So, instead of using exact `equal to' operation, we use the following statement
a @s@ E A ` IFHiEIRA
and if has the value of true, we consider and have the same values.
An array of logical values can be used to conduct operations on another numeric array of the same size. This is called masking. A mask is a logical array that selects only those elements of a main array that correspond to a true value in the mask array.
For example:
bb a I P Q Y R S T Y U V W bb a bS bb @A a sqrt@@AA
The array above is the masking array (it is the same size as ) and contains only true or flse value. Thus @A is the subarray of containing only those elements that have a true value in the corresponding element of . Masking is helpful when one is trying to do some operations on a part of a bigger array based on some logical condition.
26
3.1.4
Logical Operators
On several occasions in branching, one needs to combine multiple logical conditions into a single condition. These is done by logical operators. Logical operators combine or operate on logical variables and yield a logical true or flse result. There are ve logical operators that operate on two logical variables: AND (8 and 88), OR (| and ||), and Exclusive-OR (xor), The general form of these operations is
lI `opb lP
where lI and lP are expressions or variables. In addition there is a unary operator: NOT () with the general form
lI
The NOT operator takes the value of lI and simply returns the opposite value. Thus it changes true to flse and flse to true.
AND AND with shortcut evaluation Inclusive OR Inclusive OR with shortcut evaluation Exclusive OR NOT
lI 8 lP lI | lP xor@lIDlPA lI 88 lP lI || lP flse flse flse flse flse flse true flse true true true flse flse true true true true true true flse
With `shortcut evaluation' MATLAB evaluates the rst expression lI and then decides if evaluating the second expression lP is going to change the result of the operation. For example, if we consider the following expression.
Note:
lI a @R`SA || @ dot@IXIHHHDIXIHHHA b H A
Once MATLAB knows the value of the expression on the left of || is true, it does not matter what the result on the right is because the nal result is still going to be true. MAT-
27
LAB simply assigns the logical constant lI a value of true and moves to the next statement. Thus using shortcut evaluation can speed up your MATLAB program. However, shortcut evaluation cannot be used to combine two logical arrays. Then one must use the single | or 8.
Hierarchy of Operations
Logic operators are evaluated after all arithmetic operations and all relational operators have been evaluated. 1. All arithmetic operators are evaluated rst in the order previously described. 2. All relational operators are evaluated, working from left to right. 3. All operators are evaluated. 4. All 8 and 88 operators are evaluated, working from left to right. 5. All |, ||, and xor operators are evaluated, working from left to right.
28
if
logical expression ,
statement A ,
end
One may choose to execute a dierent section of code if the logical expression is not true. This can be done with the ifEelseEend construct, which has the syntax:
if
logical expression ,
statement A ,
else
statement B ,
end
Sometimes, one may have to check multiple conditions one after the other before deciding what section of code to execute. This can be done by adding the elseif clause to the above ifEend syntax. The general form of the ifEelseifEend construct has the following syntax:
if logical expression 1 statement group A elseif logical expression 2 statement group B elseif logical expression 3 statement group C . . . end
Here, if logical expression 1 is true, then only statement group A is executed. otherwise if logical expression 2 is true, then only statement group B is executed.
29
otherwise if
If both the logical expressions 1 and 2 are true, then only statement group A is executed. If none of the logical expressions is true, then none of the statements within the ifEelseifEend structure is executed. Another variation of this construct includes an else clause towards the end resulting in an ifEelseifEelseEend construct:
Note:
if logical expression 1 statement group A elseif logical expression 2 statement group B elseif logical expression 3 statement group C . . . else statement group D end
In this case, if none of the logical expressions 1, 2 and 3 is true, then the statement group D is executed.
Note:
3.2.1
The Nested
if
Statement
When one if branch is completely contained within the statement group of another outer if branch, the process is called nesting. In general it takes the form:
if logical expression 1 statement group A if logical expression 2 statement group B end statement group C end
In this case, statement group B is executed only if rst, the and then if logical expression 2 is true.
30
swith (switch expression ) se case expression 1, statement group A se case expression 2, statement group B ... otherwise, statement group N end
If the value of switch expression is equal to case expression 1, then `statement group A' will be executed, and the program will jump to the rst statement following the end of the swith construct. Similarly, if the value of switch expression is equal to case expression 2, then `statement group B' will be executed, and the program will jump to the rst statement following the end of the swith construct. The same idea applies for any other cases in the construct. The otherwise code block is optional. If it is present, it will be executed whenever the value of switch expression is outside the range of all the case selectors. If it is not present and the value of switch expression is outside the range of all the case selectors, then none of the code blocks will be executed. If many values of the switch expression should cause the same code to execute, all of those values may be included in a single block by enclosing them in curly brackets. In the following example, if the switch expression matches any of the three case expressions in the list, then `statement group a' will be executed.
swith (switch expression ) se {case expression 1, case expression 2, case expression 3 }, statement group A ... otherwise, statement group N end
At most one code block can be executed. After a code block is executed, execution skips to the rst executable statement after the end statement. If the switch expression matches more than one case expression, only the rst one of them will be executed. 31
Breakpoints: You can stop the execution of your program at a certain point in your code by setting a breakpoint. Once MATLAB reaches that point in the code it `freezes' execution and returns the control to the user. At this point you can check all your variables and run commands as you normally would. To proceed from a breakpoint you may press F10 to follow your code line by line or press F5 to continue execution till the next breakpoint (if any). Conditional Breakpoints: Conditional breakpoints can be set when you wish to stop execution of your code at a point depending upon certain `logical' condition being true. For example, stop only if a variable has a negative value or only for a certain value of the loop variable. Error Breakpoints: Execution stops if any errors or warnings are encountered. Check code with M-lint: M-lint checks for errors, obsolete features, unused variables etc. Proler: Shows the details of the computational time taken to execute a program. Thus one can see which parts of the program take up more time and try to make their that part of the calculation more ecient.
32
Chapter 4 Loops
As your programs start to get more complicated, you will need to follow some Program Design techniques before you can begin writing the code.
Clearly state the problem that you are trying to solve. Dene the inputs required by the program and the outputs to be produced by the program.
An algorithm is a step-by-step procedure for nding the solution to a problem. At this stage, the top-down design techniques are used.
4. 5.
Turn the algorithm into MATLAB statements. Test the resulting MATLAB program.
Algorithms are usually described using a pseudo-code (derived from pseudo meaning false or stand in, and code for program) that uses constructs such as branching and loops similar to a programming language but does not have a set syntax. We will use a mixture of MATLAB and English as pseudo-code in this class.
33
4.2 Loops
One of the strongest attributes of a computer is its ability to do fast repetitive operations on a set of data. As programmers, we use this feature through loops when we want to repeat certain parts of our program over and over again. For instance, say we want to calculate the sum of all the elements of an array e. The `brute force' way of doing this would be:
bb bb bb bb
a a a a
sume =
i=1
e(i)
Having identied the pattern, the formula can be directly coded up in MATLAB as a for loop as:
35
for
Loop
In for loops, the loop expression can take other forms also. In general, the loop expression can be any matrix. Then, MATLAB assigns one column of the matrix to the index variable and executes the statements within the body of the forEend loop, successively for as many columns there are in the matrix. Example:
for ii a S W U ii end
for ii a I P QY R S T ii end
Example:
36
The for loop construct functions as follows: 1. At the beginning of the loop, MATLAB generates the control expression. 2. The rst time through the loop, the program assigns the rst column of the expression to the loop variable index, and the program executes the statements within the body of the loop. 3. After the statements in the body of the loop have been executed, the program assigns the next column of the expression to the loop variable index, and the program executes the statements within the body of the loop again. 4. The above step 3 is repeated over an over as long as there are additional columns in the control expression. Note:
The index of the for loop must be a variable. If the expression is a scalar, then the loop will be executed one time, with the index containing the value of the scalar. If the expression is a row vector, then each time through the loop, the index will contain the next value in the vector. If the expression is a matrix, then each time through the loop, the index will contain the next column in the matrix. Upon completion of the loop, the index contains the last value used.
37
38
numers a input@9inter n rry of numersX 9A n a length@numersAY sumnum a HY sqrsum a HY for ii a IXn sumnum a sumnum C numers@iiAY sqrsum a sqrsum C numers@iiAPY end vg a sumnumGnY stddev a sqrt@@nBsqrsumEsumnumPAG@nB@nEIAAAY fprintf@9he men is 7f nd the stndrd devition is 7fF n9D vgD stddevAY
2. Searching for a number in a given array:
numers a input@9inter n rry of numersX 9A srh a input@9inter the numer to serhX 9AY lo a Y for ii a IXlength@numersA if numers@iiA aa srh lo a lo iiY end end if length@loA b H fprintf@9he numer 7d ours t the indiesX 9D srhAY fprintf@9 7d 9D loAY fprintf@9in the rryF n9AY else fprintf@9he numer 7d ws not found in the rryX 9D srhAY end
39
numers a input@9inter n rry of numersX 9A minnum a snfY mxnum a HY minlo a Y mxlo a Y for ii a IXlength@numersA if numers@iiA ` minnum minnum a numers@iiAY minlo a iiY elseif numers@iiA aa minnum minlo a minlo iiY end if numers@iiA b mxnum mxnum a numers@iiAY mxlo a iiY elseif numers@iiA aa mxnum mxlo a mxlo iiY end end fprintf@9he minimum numer isX 7d n9 fprintf@9st ws found t the following fprintf@9 7d 9D minloAY fprintf@9n9AY fprintf@9he mximum numer isX 7d n9 fprintf@9st ws found t the following fprintf@9 7d 9D mxloAY fprintf@9n9AY D minnumAY lotions in the rryX9AY D mxnumAY lotions in the rryX9AY
40
7 he size of sqr is qysxq in the loop s ii grows 7 wevef hs to llote 8 dellote memory 7 nd trnsfer dt whih tkes lot of timeF
Preallocation of arrays before the loop begins can speed up the execution.
ler llY lY 7 ith rellotion tiY sqr a zeros@IDIHHHHAY for ii a IXIHHHH sqr@iiA a iiPY end to
Alternatively, you can also use Vectorization i.e. use the etc.) to speed up the execution even more.
Note that the for loop has been replaced entirely by the array operations. MATLAB internally implements the loop for you when you use array operations. It does so using vectorized memory operations which are faster.
41
Examples:
for ii a IXS if ii aa Q rekY end fprintf@ii a 7d \n9D iiAY end disp@ind of loop39AY for ii a IXS if ii aa Q ontinueY end fprintf@ii a 7d \n9D iiAY end disp@ind of loop39AY
42
P ii a I jj jj jj ii a P jj jj jj ii a Q jj jj jj e a R IH IR
S a I a P a Q a I a P a Q a I a P a Q IH PS QS
IR QS RW
43
Note:
MATLAB associates each end statement with the latest open for loop. You cannot have an end for the outer loop before the end for the inner loop. When for loops are nested, they should have independent loop index variables. When a rek or ontinue statement appears inside a set of nested loops, then it refers to the latest open loops containing it.
Example:
ler llY a input@9inter row vetorX 9A n a length@AY for ii a IXn fprintf@9ii a 7d n9D iiAY if @ii aa QA fprintf@9yuter voop ii aa Q pss usihF n9AY ontinueY end for jj a IXn fprintf@9 jj a 7d n9D jjAY if @jj aa QA fprintf@9snner voop fyuix t jj aa QF n9AY rekY end e@iiDjjA a @iiAB@jjAY end end e
44
Figure 5.1: A complete plot with title, axis labels, legend, grid, and multiple line styles.
x a HXpiGPSXPBpiY yI a sin@PBxAY yP a PBos@PBxAY plot@xD yID 9goE9D 9wrkerize9D TFHD 9wrkeridgegolor9D 99D 9wrkerpegolor9D 9g9AY hold onY
45
plot@xD yPD 9rdE9D 9wrkerize9D TFHD 9wrkeridgegolor9D 9r9D 9wrkerpegolor9D 9g9AY title@9lot of f@xA a sin@PxA nd its derivtive9AY xlel@9x9AY ylel@9y9AY legend@9f@xA9D 9dGdx f@xA9D 9votion9D 9xorthest9AY
ezplot@9sin@xAGx9DERBpi RBpiA
46
5.1.2
Logarithmic Plots
It is possible to plot data on logarithmic scales as well as linear scales. There are four possible combinations of linear and logarithmic scales on the x and y axes, and each combination is produced by a separate function. 1. The plot function plots both x and y data on linear axes. 2. The semilogx function plots x data on logarithmic axes and y data on linear axes. 3. The semilogy function plots x data on linear axes and y data on logarithmic axes. 4. The loglog function plots x and y data on logarithmic axes.
5.1.3 Subplots
It is possible to place more than one set of axes on a single gure, creating multiple
This command divides the current gure into m n equal-sized regions, arranged in m rows and n columns, and creates a set of axes at position p to receive all current plotting commands. The subplots are numbered from left to right and from top to bottom. For example, the command suplot@PD QD RA would divide the current gure into six regions arranged in two rows and three columns, and create an axis in position 4 (the lower left one) to accept new plot data. Example: Figure 5.2 is produced by the following code:
x a HXpiGQHXPBpiY yI a sin@PBxAY yP a PBos@PBxAY figure@IA suplot@PDPDIA plot@xD yID 9kE9D 9vineidth9D PFHAY xlel@9x9AY ylel@9f@xA9AY suplot@PDPDPA semilogx@xD yID 9E9D 9vineidth9D QFHA xlel@9x9AY ylel@9f@xA9AY suplot@PDPDQA
47
plot@xD yPD 9rEo9D 9vineidth9D PFHAY xlel@9x9AY ylel@9dGdx f@xA9AY xis@H T EQ QAY suplot@PDPDRA plot@xD yPD 9kd9D 9wrkerize9D TFHD 9wrkeridgegolor9D 9r9D 9wrkerpegolor9D 9g9AY xlel@9x9AY ylel@9dGdx f@xA9AY xis@H T EQ QAY
5.1.4
Matlab can create multiple Figure Windows, with dierent data displayed in each window. Window is identied by a gure number, which is a small positive integer. The rst Figure Window is Figure 1, the second is Figure 2, etc. One of the Figure Windows will be the current gure, and all new plotting commands will be displayed in that window. The current gure is selected with the figure function. This function takes the form figure@nA, where n is a gure number. When this command is executed, Figure n becomes the current gure and is used for all plotting commands. The gure is automatically created if it does not already exist. The current gure may also be selected by clicking on it with the mouse.
48
5.1.5
The print command can be used to save a plot as a graphical image by specifying appropriate options and a le name.
Option Description
dps dps deps deps djpeg dtiff dpng
PostScript for black and white printers PostScript for color printers Encapsulated PostScript Encapsulated Color PostScript JPEG image Compressed TIFF image Portable Network Graphic color image
49
plot3
function
This function plots a 3-D curve by connecting (x, y, z ) triplets with line segments (similar to the plot command which connects (x, y ) pairs). General format:
plotQ@xD yD zA}
where x, y, and z are vectors of equal length containing the locations of data points to plot. Figure 5.3 is produced by the following code:
z a HXpiGSHXIHBpiY plotQ@sin@zADos@zADzAY
50
5.2.2
The
meshgrid, mesh
and
surf
commands
For plotting a function of two variables z@xDyA we use the mesh and surf commands. Figure 5.4 and Figure 5.5 are produced by the mesh and surf functions in the following code.
Note: The meshgrid command is only used to generate the x and y arrays that represent
51
5.2.3
Another way to visualize a function of two variables is to use contour plots. MATLAB has can generate contour plots with functions such as: ontour@A, ontourQ@A and ontourf@A. A sample code and its output for the three functions is shown below.
xD yD z a peks@SHAY suplot@PDPDIAY surf@xD yD zAY title@9surf9A suplot@PDPDPAY ontour@xD yD zAY title@9ontour9A suplot@PDPDQAY ontourQ@xD yD zAY title@9ontourQ9A suplot@PDPDRAY ontourf@xD yD zAY title@9ontourf9A
52
5.2.4
Another example of a repetitive process is encountered when one is trying to generate an animation (movie) of plots. Generating a movie can be done rst creating a plot and then over-writing it with another (slightly dierent) plot and doing this repeatedly over and over again.
dely a piGSHY t a HXdelyXPBpiY yI a sin@PBtAY yP a PBos@PBtAY for ii a IXlength@tA hold off plot@t@IXiiAD yI@IXiiAD 9goE9D 9wrkerize9D TFHD 9wrkeridgegolor9D FFF 99D 9wrkerpegolor9D 9g9AY hold onY plot@t@IXiiAD yP@IXiiAD 9rdE9D 9wrkerize9D TFHD 9wrkeridgegolor9D FFF 9r9D 9wrkerpegolor9D 9g9AY xis@H PBpi EP PAY text@SFHDIFVD9t a 9 numPstr@t@iiAAAY puse@delyAY end
The xis command is needed to keep the y-axis constant during the animation. The text command displays the time and the puse command allows the user to see each plot for the specied dely (in seconds) before it is changed. 3-D plots can also be animated. For example:
x y a meshgrid@EpiXpiGIHXpiDEpiXpiGIHXpiAY figure@IAY lfY for t a IXPH 7 voop over time limits for nimtion z a sin@tGPHBPBpiABos@xAFBsin@yAY 7 rete the z vlues surf@xD yD zAY 7 plot the surfe t this instnt xis@Epi pi Epi pi EP PAY 7 set xis limits text@PDEPDPD9ta9 numPstr@tAAY 7 output text puse@HFIAY 7 puse for users to see the imge end
53
funtion [outarg1, outarg2, ...] a fnme@inarg1, inarg2, ... A 7 rI omment line 7 yther omment lines @ixeutle odeA FFF @returnA @endA
54
For example, suppose in a Matlab program, many times you need convert Spherical coordinates, (r, , ), to Cartesian coordinates, (x, y, z ). Your code may look like this:
FFF 7 onverts from @rID thetID phiIA to @xID yID zIA zI a rIBos@phiIAY xI a rIBsin@phiIABos@thetIAY yI a rIBsin@phiIABsin@thetIAY FFF 7 onverts from @rPD thetPD phiPA to @xPD yPD zPA zP a rPBos@phiPAY xP a rPBsin@phiPABos@thetPAY yP a rPBsin@phiPABsin@thetPAY FFF 7 onverts from @rQD thetQD phiQA to @xQD yQD zQA zQ a rQBos@phiQAY xQ a rQBsin@phiQABos@thetQAY yQ a rQBsin@phiQABsin@thetQAY FFF
Alternately if a user dened function, which converts from Spherical coordinates to Cartesian coordinates, had been used, your code may look like this:
FFF 7 onverts from @rID thetID phiIA to @xID yID zIA [xID yID zI] a pherilPgrtesin@rID thetID phiIAY FFF 7 onverts from @rPD thetPD phiPA to @xPD yPD zPA [xPD yPD zP] a pherilPgrtesin@rPD thetPD phiPAY FFF 7 onverts from @rQD thetQD phiQA to @xQD yQD zQA [xQD yQD zQ] a pherilPgrtesin@rQD thetQD phiQAY FFF where function pherilPgrtesin is dened in the Matlab script le pherilPgrtesinFm. funtion [xD yD z] a pherilPgrtesin@rD thetD phiA 7 onverts from @rD thetD phiA to @xD yD zAF z a rBos@phiAY x a rBsin@phiABos@thetAY y a rBsin@phiABsin@thetAY returnY
55
Notes
1. The funtion statement species the name of the function and the input and output argument lists. The input argument list appears in parentheses after the function name, and the output argument list appears in brackets to the left of the equal sign. If there is only one output argument, the brackets can be dropped. 2. Matlab function should be placed in a le with the same name (including capitalization) as the function, and the le extent Fm. For example, if a function is named wyfun, then that function should be placed in a le named wyfunFm. 3. The input argument list is a list of names representing values that will be passed from the caller to the function. These names are called dummy arguments. They are just placeholders for actual values that are passed from the caller when the function is invoked. Similarly, the output argument list contains a list of dummy arguments that are placeholders for the values returned to the caller when a function nishes executing. 4. A function is invoked by naming it in an expression together with a list of actual arguments. A function may be invoked by typing its name directly in the Command Window or by including it in a script le or another function. The name in the calling program must exactly match the function name (including capitalization). When the function is invoked, the value of the rst actual argument is used in place of the rst dummy argument, and so forth for each other actual argument/dummy argument pair. 5. Execution begins at the top of the function and ends when either a return statement, an end statement, or the end of the function is reached. The return statement or the end statement is not actually required in most functions. The only information returned from the function is contained in the output arguments. So, each item in the output argument list must appear on the left side of at least one assignment statement in the function. When the function returns, the values stored in the output argument list are returned to the caller. 6. Matlab function is a special type of M-le that runs in its own independent workspace. For example, the variable dened in the main program, i.e. x, has nothing to do with the variable in a function although they may have the same name x. In other words, the change of the value of x in the function does not change the value of x in the main program or vice versa. 7. The initial comment lines in a function serve a special purpose. The rst comment line after the function statement is called the H1 comment line. It should always contain a one-line summary of the purpose of the function. The special signicance of this line is that it is searched and displayed by the lookfor command. The comment lines from the H1 line until the rst blank line or the rst executable statement are displayed by the help command. They should contain a brief summary of how to use the function.
56
Examples:
Searching
funtion lotions a myserh@rrD numPserhA 7 his funtion serhes for given numer @numPserhA in given rry @rrAF 7 st returns n rry of the indies lotions where the numer is foundF lotions a Y tol a IeEIRY n a length@rrAY for ii a IXn if s@rr@iiAEnumPserhA`tol lotions a lotions iiY end end
57
Sorting
funtion sortedrr a mysort@inprrA 7 his funtion sorts given rry of numers @inprrA using seletion sort n a length@inprrAY for ii a IXnEI 7 inprr 7 puse min a inprr@iiAY lo a iiY for jj a ii C IXn if inprr@jjA`min lo a jjY min a inprr@jjAY end end if lo ~a ii 7 xeed to swp inprr@loA nd inprr@iiA inprr@loA a inprr@iiAY inprr@iiA a minY end end sortedrr a inprrY
58
funtion out a smple@D A fprintf@sn smpleX a 7fD a 7f 7f \n9D D AY a @IA C PBY a FBY out a C @IAY fprintf@sn smpleX a 7fD a 7f 7f \n9D D AY
A simple test program to call this function is shown below.
a PY a [T R]Y fprintf@fefore smpleX a 7fD a 7f 7f \n9D D AY out a smple@D AY fprintf@efter smpleX a 7fD a 7f 7f \n9D D AY fprintf@efter smpleX out a 7f \n9D outAY
When this program is executed, the results are:
fefore smpleX a PFHHHHHHD a TFHHHHHH RFHHHHHH sn smpleX a PFHHHHHHD a TFHHHHHH RFHHHHHH sn smpleX a IHFHHHHHHD a THFHHHHHH RHFHHHHHH efter smpleX a PFHHHHHHD a TFHHHHHH RFHHHHHH efter smpleX out a UHFHHHHHH
Note that and were both changed inside the function smple, but those changes had eect on the values in the calling program.
no
59
Global variables are declared using the keyword glol and can be used within all functions that declare them as global. They are present in a declaring function's workspace but they are not lost when the function exits after completion. Persistent variables are local to some function that declares them with the keyword persistent. The dierence between persistent variables and normal function variables is that when a function is called again and again, persistent variables preserve their value between calls.
fevl@'functionname', x1, ... xN A Evaluates the specied function functionname with inputs x1, ... evl@'string' A Executes the given 'string' as a MATLAB statement. Examples fzeroD qudD fminnd
xN .
60
funtion outsum a sumre@nA 7 sumnonre X lultes the sum of the first n integers using reursion if n`I error@9irrorX n must e positive n9AY elseif naaI outsum a IY else outsum a sumre@nEIA C nY end
In the end, when sumre@PA calls sumre@IA, recursion stops and the value of sumre@IA = 1 is returned. Then sumre@PA adds this value to 2 and returns 3 and so on back upto the level of the original call. 2. Recursion Terminating Condition: Every recursive function must have a terminating condition. In the above example the terminating condition is chosen as naaI. If the terminating condition is missing, then the recursive function would keep calling itself an innite number of times. 61
Examples:
Factorial: n! = 1 2 3 ... (n 1) n
funtion outft a ftre@nA 7 ftreX lultes the ftoril of n integer using reursion if n`I error@9irrorX n must e positive n9AY elseif naaI outft a IY else outft a ftre@nEIA B nY end
Calculation of a Power series: For example, the exponential of a real number x can be obtained using the following innite sum: xn x 2 x3 x4 + + + + + ex = 1 + x + 2! 3! 4! n! A recursive MATLAB user dened function that takes as input the values of x and n and returns two outputs ftn expxn which are n! and ex upto n terms can be implemented as:
funtion ftn expxna reexp@xDnA 7his funtion tkes inputs @xDnA to lulte n3 nd ex with n terms nd outputs if n`H || n ~around@nA error@9irrorX n must e nonEnegtive integer9AY elseif naaH 7terminting ondition ftn a IY expxn a IY else 7reursive ll for @nEIA3 nd ex with nEI terms fnmI expnmI a reexp@xDnEIAY ftn a fnmIBnY expxn a expnmI C xnGftnY 7 get n3 7 get ex with n terms
end
Note that we combined multiple outputs in the above recursive function for better eciency (instead of having dierent recursive calls for summing and factorial).
62
funtion outfn a fiore@nA 7 fioreX lultes the first n fioni numers if n`I error@9irrorX n must e positive n9AY elseif naaI outfn a HY elseif naaP outfn a H IY else fnmI a fiore@nEIAY outfn a fnmI@nEIA C fnmI@nEPAY outfn a fnmI outfnY end
The following MATLAB code computes and displays the rst n Fibonacci numbers using Loops and Recursion:
ler llY lY n a input@9inter the numer of pioni numers requiredX 9AY fprintf@9pioni numers with voopsX n9AY for ii a IXn if iiaaI fn a HY elseif iiaaP fnmI a HY fn a IY else fnew a fn C fnmIY fnmI a fnY fn a fnewY end fprintf@97d 9D fnAY end fprintf@9n9AY fprintf@9pioni numers with eursionX n9AY fprintf@97d 9Dfiore@nAA fprintf@9n9AY
63
D D D FFF
a textred@filenmeD formtD nA
where filenme is the name of the le to open, formt is a string containing a description of the type of data in each column, and n is the number of lines to read. If n is missing, the function reads to the end of the le. The format string contains the same types of format descriptors as function fprintf. Note that the number of output arguments must match the number of columns that you are reading. For example, suppose that le inputFdt contains the following data:
64
Function textred is much more exible than the lod command. The lod command assumes that all of the data in the input le is of a single type it cannot support dierent types of data in dierent columns. In addition, it stores all of the data into a single array. In contrast, the textred function allows each column to go into a separate variable, which is much more convenient when working with columns of mixed data.
Data in formatted les is translated into characters that can be read directly by a user. However, formatted I/O operations are slower and less ecient than binary I/O operations. Binary data consists of the actual bit (0,1) patterns that are used to store the data in computer memory. Reading and writing binary data is very ecient, but a user cannot read the data stored in the le.
We will discuss both types of I/O operations later in this chapter.
fopen
Function
Then fopen function opens a le and returns a le id number that MATLAB has assigned to it. The basic forms of this statement are
fid a fopen@filenmeD permissionA fidD messge a fopen@filenmeD permissionA fidD messge a fopen@filenmeD permissionD formtA
where filenme is a string specifying the name of the le to open, permission is a character string specifying the mode (read, write or append) in which the le is opened, and formt is 65
an optional string specifying the numeric format of the data in the le. The formt option is rarely used. If the open is successful, fid will contain a positive integer after this statement is executed, and messge will be an empty string. If the open fails, fid will contain a EI after this statement is executed, and messge will be a string explaining the error. The possible permission strings are shown in the following table.
Open an existing le for reading only (default). Open an existing le for reading and writing. Delete the contents of an existing le (or create a new le) and open it for writing only. Delete the contents of an existing le (or create a new le) and open it for reading and writing. Open an existing le (or create a new le) and open it for writing only, appending to the end of the le. Open an existing le (or create a new le) and open it for reading and writing, appending to the end of the le.
On some platforms such as PCs, it is important to distinguish between text les and binary les. If a le is to be opened in text mode, then a t should be added to the permissions string (for example, rt9 or rtC). If a le is to be opened in binary mode, a may be added to the permissions string (for example, r9), but this is not actually required, since les are opened in binary mode by default. This distinction between text and binary les does not exist on Unix or Linux computers, so the t and is never needed on those systems. Some examples of correct fopen functions are shown below.
66
proper form of the fopen function for an output le is we want to replace pre-existing data. The t9 permissions string species that we want to append to an existing text le. If it is already exists, then it will be opened and new data will be appended to the currently existing information. This is the proper form of the fopen function for an output le if we don't want replace pre-existing data.
fclose
Function
67
feof : Returns logical true(1) or false(0) depending upon whether the end of le for le id fid has been reached or not.
eofstt a feof@fidA
frewind: To reset the le position at the beginning of the le.
frewind@fidA
ftell: Returns the current position within a le using a non-negative integer denoting bytes from the beginning.
position a ftell@fidA
fseek: To relocate the le position by offset number of bytes relative to a position specied by origin which can be @9of9D 9of9D 9eof9A denoting beginning of le, current position in le and end of le.
68
fprintf
Function
The fprintf function writes formatted data in a user-specied format to a le. Its form is
ount a fprintf@fidD formtD vlID vlPD FFFA fprintf@formtD vlID vlPD FFFA
where fid is the le id of a le to which the data will be written, and formt is the format string controlling the appearance of the data. If fid is missing, the data is written to the standard output device (the Command Window). This is the form of fprintf that we have learned before. The format string species the alignment, signicant digits, eld width, and other aspects of output format. It can contain ordinary alphanumeric characters along with special sequences of characters that specify the exact format in which the output data will be displayed. A single % character always marks the beginning of a format. If an ordinary % is to be printed out, then it must appear in the format string as %%. After the % character, the format can have a ag, a eld-width and precision specier, and a conversion specier. The % character and the conversion specier are always required in any format, while the eld, eld-width, and precision specier are optional. The possible conversion speciers are listed in the following table.
Single character String of characters Decimal notation (signed) Decimal notation (unsigned) Exponential notation using a lowercase e Exponential notation using an uppercase i Fixed-point notation The more compact of 7e or 7f Same as 7g, but using an uppercase i Octal notation (unsigned) Hexadecimal notation (using lowercase letters Ef) Hexadecimal notation (using uppercase letters eEp)
If a eld width and precision are specied in a format, then the number before the decimal point is the eld width, which is the number of characters used to display the number. The number after the decimal point is the precision, which is the minimum number of signicant digits to display after the decimal point. Make sure that there is a one-to-one correspondence between the types of the data in an fprintf function and the types of the format conversion speciers in the associated format string; otherwise, your program will produce unexpected results. 69
7.5.2
The
fscanf
Function
The fsnf function reads formatted data in a user-specied format from a le:
n Read exactly n values. After this statement, rry will be a column vector containing n values read from the le. snf Read until the end of the le. After this statement, rry will be a column vector containing all of the data until the end of the le. mD n Read exactly m n values, and format the data as an m n array.
The format string species the format of the data to be read. It can contain ordinary characters along with format conversion speciers. The fsnf function compares the data in the le with the format conversion speciers in the format string. As long as the two match, fsnf converts the value and stores it in the output array. The process continues until the end of the le or until the amount of data in size has been read, whichever comes rst. If the data in the le does not match the format conversion speciers, the operation of fsnf stops immediately. The format conversion speciers for fsnf are basically the same as those for fprintf.
7.5.3 The
fgetl
and
fgets
Functions
The fgetl and fgets functions read the next line of input from the le specied by le id fid and return a character array (string), line as output. Their general form is
70
fwrite
Function
The fwrite function writes binary data in a user-specied format to a le. Its form is
hrBI9 signed hr9 unsigned hr9 integerBI9 integerBP9 integerBR9 integerBV9 integerBI9 integerBP9 integerBR9 integerBV9 relBR9 relBV9
8-bit character 8-bit signed character 8-bit unsigned character 8-bit integer 16-bit integer 32-bit integer 64-bit integer 8-bit unsigned integer 16-bit unsigned integer 32-bit unsigned integer 64-bit unsigned integer 32-bit oating point 64-bit oating point N-bit signed integer, 1 <= N <= 64 N-bit unsigned integer, 1 <= N <= 64
Meaning
71
The optional argument skip species the number of bytes to skip in the output le before each write. Note that if preision is a bit format like itx9 or uitx9, skip is specied in bits instead of bytes.
7.6.2 The
fread
Function
The fred function reads binary data in a user-specied format from a le, and returns the data in a (possibly dierent) user-specied format. Its form is
rryD ount a fred@fidD sizeD preisionA rryD ount a fred@fidD sizeD preisionD skipA
where fid is the le id of a le opened with the fopen function, size is the number of values to read, rry is the array to contain the data, and ount is the number of values read from the le. The optional argument size species the amount of data to be read from the le. There are three versions of this argument:
n Read exactly n values. After this statement, rry will be a column vector containing n values read from the le. snf Read until the end of the le. After this statement, rry will be a column vector containing all of the data until the end of the le. mD n Read exactly m n values, and format the data as an m n array.
The preision argument species both the format of the data on the disk and the format of the data array to be returned to the calling program. The general form of the precision string is
diskpreision ab rrypreision9
where diskpreision and rrypreision are both among the precision strings found in the previous table. The rrypreision value can be defaulted. If it is missing, then the data is returned in a doule array. There is also a shortcut form of this expression if the disk precision and the array precision are the same: Bdiskpreision9.
72
In addition to the solution of linear sets of equations, Matlab oers numerous matrix functions that are useful for solving numerical linear algebra problems. Some of these functions are listed below:
hol@eA Cholesky factorization. ond@eA Matrix condition number. det@eA Determinant. eig@eA Vector of eigenvalues. D h a eig@eA Matrix of eigenvectors, and diagonal matrix containing eigenvalues. inv@eA Matrix inverse. vD a lu@eA LU decomposition. norm@eD typeA Matrix and vector norms. rnk@eA Matrix rank. shur@eA Schur decomposition. svd@eA Singular values. D D a svd@eA Singular value decomposition. tre@eA Sum of matrix diagonal elements.
mx@xA If x is a vector then the function returns the largest value in x. If x is a matrix then the function returns a row vector containing the maximum element from each column. D a mx@xA In this form, if x is a vector, then the function stores the maximum value of x in a scalar , and the index of the maximum value in the scalar . If there are several identical maximum values, the index of the rst one found is returned. If x is a matrix, then the function stores the maximum values of x in a vector and the indices of the maximum values in a vector . mx@xD DIA The function returns a row vector containing the maximum element from each column.
74
mx@xD DPA The function returns a column vector containing the maximum element from each row. Replacing mx with min in the above functions gives the corresponding functions for nding minimums. men@xA If x is a vector, this function computes the average value of the elements of the vector x. If x is a matrix, this function computes a row vector that contains the average value of each column. men@xDIA The function returns a row vector containing the average value from each column. men@xDPA The function returns a column vector containing the average value from each row. medin@xA If x is a vector, this function computes the median value of the elements of the vector x. If x is a matrix, this function computes a row vector that contains the median value of each column. medin@xDIA The function returns a row vector containing the median value from each column. medin@xDPA The function returns a column vector containing the median value from each row. sum@xA If x is a vector, this function returns the sum of the elements of x. If x is a matrix, this function returns a row vector that contains the sum of each column. sum@xDIA The function returns a row vector containing the sum of elements from each column. sum@xDPA The function returns a column vector containing the sum of elements from each row. sort@xA If x is a vector then this function sorts the values into ascending order. If x is a matrix then this function sorts each column into ascending order. D a sort@xA The sorted values are returned to the matrix and reordered indices are stored in the matrix . std@xA If x is a vector, this function computes the standard deviation of the values of x. If x is a matrix, this function computes a row vector containing the standard deviation of each column. vr@xA If x is a vector, this function computes the variance of the values of x. If x is a matrix, this function computes a row vector containing the variance of each column.
75
8.3 Polynomials
Matlab provides a number of functions for manipulating polynomials. We will introduce a couple of those functions.
8.3.1 Roots
Finding the roots of a polynomial is a problem common to many disciplines. Matlab solves this problem and nds the roots of a polynomial by using function roots. In Matlab a polynomial is represented by a row vector of its coecients in descending order. For example, the polynomial x4 12x3 + 0x2 + 25x + 116 is represented by a vector
p a I EIP H PS IITY
Note that terms with zero coecients must be included. Matlab has no way of knowing which terms are zero unless you specically identify them. Given this form, the roots can be found by
r a roots@pAY
where r is a column vector containing the roots of the polynomial. Matlab adopts the convention that polynomials are row vectors and roots are column vectors.
8.3.2 Curve Fitting
In numerous application areas, one is faced with the task of tting a curve to measured data. Sometimes the chosen curve passes through the data points, but at other times the curve comes close to, but does not necessarily pass through the data points. In the most common situation, the curve is chosen so that the sum of the squared errors at the data points is minimized. This choice results in a least squares curve t. It is straightforward and common to use a polynomial as the basis function for the least squares curve tting. In Matlab, the function polyfit solves the least squares polynomial curve-tting problem. To illustrate the use of this function, let's start with the data
x a H HFI HFP HFQ HFR HFS HFT HFU HFV HFW IFHY y a EHFRS IFWV QFPV TFIT UFHV UFQR UFTT WFST WFRV WFQH IIFPHY
To use polyfit, we must give it the above data and the order or degree of the polynomial we wish to best t the data. If we choose n = 1 as the order, the best straight-line approximation will be found. This is often called linear regression. If we choose n = 2 as the order, a quadratic polynomial will be found. For example, let's choose a quadratic polynomial:
n a PY p a polyfit@xD yD nAY
76
The output of polyfit is a row vector of the polynomial coecients, which are EWFVIRU PHFIQQV EHFHQPU stored in p. This means the solution is y (x) = 9.8147x2 + 20.1338x 0.0327. Figure 8.1, which is created by the following code, shows the original data and the tted curve.
xi a linspe@HD ID IHHAY yi a polyvl@pD xiAY figure@IA plot@xD yD 9Eo9D xiD yiD 9EE9A xlel@9x9AY ylel@9y a f@xA9AY title@9eond yrder gurve pitting9AY
where function polyvl is used to evaluate the polynomial at a set of data points.
Figure 8.1: Original data points and the second order curve tting.
77
8.4 Integration
Matlab provides functions for numerically approximating the integral of a function. These functions are qud, qudl, and dlqud.
qud Numerically evaluate integral, adaptive Simpson quadrature. qudl Numerically evaluate integral, adaptive Lobatto quadrature. dlqud Numerically evaluate double integral. f (x) = ex occurs frequently in physics problems but cannot be integrated analytically. 1 Let's show how to use function qud to compute 0 f (x)dx numerically.
First, we need to dene the function to be integrated. The function must support a vector 2 input argument and return a vector of outputs for a vector inputs. For example, f (x) = ex is dened in myfunFm as
2
Matlab computes the time history of a set of coupled rst-order dierential equations with known initial conditions. These problems are called initial value problems and have the form = f (t, y) y y(t0 ) = y0 which is vector notation for the set of dierential equations
where y i = dyi /dt, n is the number of rst-order dierential equations, and yi0 is the initial condition associated with the ith equation. When an initial value problem is not specied as a set of rst-order dierential equations, it must be rewritten as one. For example, consider the classic van der Pol equation
x (1 x2 )x +x=0
where is a parameter greater than zero. If we choose y1 = x and y2 = dx/dt, the van der Pol equation becomes y 1 = y2 2 )y2 y1 y 2 = (1 y1 We will demonstrate Matlab ODE solvers by solving this problem.
8.5.2 ODE Solvers
Matlab oers seven initial value problem solvers. We will talk about two of them.
odeRS An explicit one-step Runge Kutta medium-order (4th- to 5th-order) solver. Suitable for non-sti problems that require moderate accuracy. This is typically the rst solver to try on a new problem. odeISs An implicit, multistep numerical dierentiation solver of varying order (1stto 5th-order). Suitable for sti problems that require moderate accuracy. This is typically the solver to try if odeRS fails or is too inecient.
8.5.3 Basic Use
Before a set of dierential equations can be solved, they must be coded in a function M-le. That is, the le must accept a time t and a solution y and return values for the derivatives. For the van del Pol equation, this ODE le can be written as follows.
funtion ydot a vdpol@tD yA 7 his funtion @ydotaf@tDyAA defines the system of yhis you re trying to solveF 7 he input 9y9 n e xxI vetorY hus 9ydot9 must lso e xxI vetor mu a PY 7 some onstnt yIdot a y@PAY yPdot a muB@IEy@IAPABy@PA E y@IAY ydot a yIdotY yPdotY
Note that the input arguments are t and y but that the function does not use t. Note also that the output ydot must be a column vector. Given the above ODE le, this set of ODEs is solved by the following statements.
tspn a H PHY 7 time spn to integrte over yH a PY HY 7 initil onditions @must e olumnA tD y a odeRS@9vdpol9D tspnD yHAY plot@tDy@XDIAD9FE9DtDy@XDPAD9gFE9A legend@9y9D9dyGdt9A
79
where t contains the time points, y@XDIA contains the solution of x@tA, and y@XDPA contains the values of dxGdt. sliding down a rotating support as shown in 8.2.
Example 1: In a dynamic problem, we have the following governing equation for a bowl
2 r 0 r = g sin(0 + 0 t)
where r is the distance of bowl away from the support end. Initial distance L = 2m ; Angular rotating speed of slope 0 = 0.1 rad/s ; Initial angle of the slope 0 = 0.2 rad. g is the acceleration due to gravity. Solve for r(t) and r (t) using Matlab. Verify with the exact solution given by:
r(t) = r (t) =
g cos0 g g sin0 cosh(0 t) sinh(0 t) + 2 sin(0 + 0 t) 2 2 20 20 20 g sin0 g cos0 g L0 sinh(0 t) cosh(0 t) + cos(0 + 0 t) 20 20 20 L
First we need convert this second order ODE to a set of rst-order dierential equations. Let y1 = r and y2 = dr/dt, we have
y 1 = y2 y 2 = 2 y1 g sin(0 + 0 t)
The code for the derivative function as well as the statement for solving the ODEs are listed below.
80
funtion ydot a owlonslope@tD yA wH a HFIY thetH a HFPY g a WFVY ydot a y@PAY wHPBy@IA E gBsin@thetHCwHBtAY
AND
ler llY lose llY v a PFHY tspn a H IFHY yH a vY HY g a WFVY wH a HFIY thetH a HFPY tD y a odeRS@9owlonslope9D tspnD yHAY ti a linspe@HD IFHD IHHAY ri a @v E gGPGwHPBsin@thetHAABosh@wHBtiA E FFF gGPGwHPBos@thetHABsinh@wHBtiA C gGPGwHPBsin@thetHCwHBtiAY ridot a @vBwH E gGPGwHBsin@thetHAABsinh@wHBtiA E FFF gGPGwHBos@thetHABosh@wHBtiA C gGPGwHBos@thetHCwHBtiAY figure@IA plot@tD y@XDIAD 9FE9D tiD riD 9kE9AY xlel@9t9AY ylel@9distne r9AY legend@9wtl xumeril olution9D9enlytil ixt olution9A figure@PA plot@tD y@XDPAD 9FE9D tiD ridotD 9kE9AY xlel@9t9AY ylel@9owl speed9AY legend@9wtl xumeril olution9D9enlytil ixt olution9A
Figure 8.3 shows the distance r versus time t. In this gure, analytical solution is also given for comparison. Figure 8.4 shows the speed of the bowl r versus time t.
81
82
the change in concentration three species in a tank. The reactions A B C occur within the tank. The constants k1 , and k2 describe the reaction rate for A B and B C respectively. The following ODEs are obtained:
dCb dt dCa dt
= k1 Ca = k1 Ca k2 Cb dCc = k2 Cb dt
Where k1 = 1 hr1 and k2 = 2 hr1 and at time t = 0, Ca = 5 mol and Cb = Cc = 0 mol. Solve the system of equations and plot the change in concentration of each species over time. Select a time interval [0 5] for the integration.
Solution:
ler llY lose llY tspn a H SY yH a S H HY tD y a odeRS@9onentrtion9D tspnD yHAY figure@IA plot@tD y@XDIAD 9rE9D tD y@XDPAD 9EE9D tD y@XDQAD 9kB9A xlel@9ime @hrA9AY ylel@9onentrtion of eh speies @molGhrA9AY legend@9g9D9g9D9g9D9votion9D9ist9AY
Figure 8.5 shows the result.
83
84
85
The governing dierential equation along with initial conditions for this system is
funtion w g u v d uH vH spn delt a strdyninput 7 snitiliztion m a IFHY k a IFHY v a HFSY d a HFSY w a m H HY H m HY H H mGPFHY u a PBk Ek HY Ek PBk EkY H Ek kY lph a HFHY et a HFHY g a lphBw C etBuY 7 snitil onditions uH a HFHSY HFHSY HFHSY vH a HY HY HY 7uH a HY HY HY vH a HFHSY HFHSY HFHSY 7uH a HY HY HY vH a HY HY HY 7 hefine time spn nd time step spn a PSFHY delt a HFIY
The externally applied force can also be dened as a function of time t in strdynforce.m:
Figure 9.2: Initial conguration of the three-oor building. The following two methods can be used to solve the Structural Dynamics problem:
= f (t, y ) y (t) = f (t, y (t)) y y1 (t) 1 (t) = x (t) and , y1 (t) = x(t) ; y2 (t) = y y2 (t) 1 (t) = y2 (t) y 2 (t) = M 1 [F (t) C y2 (t) K y1 (t)] y
Now we can code this using odeRS@A. Dene the standard form of the equation to be solved: strdynfun.m:
where y (t) =
n a size@wDIAY yI a y@IXnAY yP a y@nCIXPBnAY yIdot a yPY yPdot a inv@wAB@pEuByIEgByPAY ydot a yIdotY yPdotY
Main program strdyn.m
ler llY lose llY 7 snitiliztion w g u v d uH vH spn a strdyninputY tmtD ymt a odeRS@9strdynfun9D H spnD uHY vHAY plot@tmtDymt@XDIAD9r9D tmtDymt@XDPAD99D tmtDymt@XDQAD9k9AY xlel@9time9AY ylel@9hisplement9AY legend@9tory I9D9tory P9D9tory Q9D9votion9D9outhist9A
88
The central dierence method with a time step t is used for solving the second order dierential governing equation. The calculation steps are listed below:
x1
(t)2 0 0 + x = x0 tx 2
Ke =
4. Loop over time steps i = 1:N
1 1 M+ C 2 (t) 2t
(a) Compute the next state (at ti+1 ) of the system in terms of the two previous states ti and ti1 :
1 xi+1 = Ke Fi K
2 M (t)2
xi
1 1 M C xi1 (t)2 2t
(b) Store the solution and move to the next time step. Main Program strdyncd.m
ler llY lose llY 7 snitiliztion w g u v d uH vH spn delt a strdyninputY 7 hefine the time steps t a EdeltXdeltXspnY nsteps a length@tAY 7 glulte the vetor vlue of initil elertion p a strdynfore@HAY H a inv@wAB@p E gBvH E uBuHAY 7 hefine mtrix storing the solutions 7 he rows of the mtrix re the degrees of freedom
89
7 he olumns of the rry re the stte of the system in time sol a zeros@QD nstepsAY 7 he seond olumn is the position t t a H sol@XDPA a uH@XAY 7 gompute one kwrd step @t a Ehelt tAD nd store x@Ehelt tA in the 7 first olumn of the solution mtrix sol@XDIA a uH@XA E deltBvH@XA C deltPGPFHBH@XAY 7 gompute the effetive stiffness mtrix nd store the inverse ueff a wG@deltPA C gG@PFHBdeltAY ueffinv a inv@ueffAY 7 wrh the eqution forwrdD reting new steps y ssigning the next 7 stte of the system s funtion of the two previous sttes for iiaQXnsteps p a strdynfore@t@iiAAY sol@XDiiA a ueffinvB@p E @uEPFHBwG@deltPAABsol@XDiiEIA FFF E @wG@deltPAEgG@PFHBdeltAABsol@XDiiEPAAY end 7 lot the time history of the displements of eh floor figure@IAY plot@t@PXnstepsAD sol@IDPXnstepsAD 9rE9D 9vineidth9D IFSA hold on plot@t@PXnstepsAD sol@PDPXnstepsAD 9E9D 9vineidth9D IFSA plot@t@PXnstepsAD sol@QDPXnstepsAD 9kE9D 9vineidth9D IFSA xlel@9time9AY ylel@9hisplement9AY legend@9tory I9D9tory P9D9tory Q9D9votion9D9outhist9A puseY 7 enimtion xpI a linspe@HD vD IHAY xpP a linspe@vD PBvD IHAY xpQ a linspe@PBvD QBvD IHAY oefwtI a H H H IY @vAQ @vAP v IY H H I HY QB@vAP PB@vA I HY oefwtP a vQ vP v IY @PBvAQ @PBvAP PBv IY QBvP PBv I HY FFF QB@PBvAP PB@PBvA I HY oefwtQ a @PBvAQ @PBvAP @PBvA IY @QBvAQ @QBvAP @QBvA IY FFF QB@PBvAP PB@PBvA I HY QB@QBvAP PB@QBvA I HY invoefwtI a inv@oefwtIAY invoefwtP a inv@oefwtPAY
90
invoefwtQ a inv@oefwtQAY figure@PAY for iiaPXnsteps dI a sol@IDiiAY dP a sol@PDiiAY dQ a sol@QDiiAY oefI a invoefwtIBHY dIY HY HY oefP a invoefwtPBdIY dPY HY HY oefQ a invoefwtQBdPY dQY HY HY ypI a polyvl@oefID xpIAY ypP a polyvl@oefPD xpPAY ypQ a polyvl@oefQD xpQAY plot@ypID xpID 9E9D 9vineidth9D PAY hold onY plot@ypPD xpPD 9E9D 9vineidth9D PAY plot@ypQD xpQD 9E9D 9vineidth9D PAY plot@ypICdD xpID 9E9D 9vineidth9D PAY plot@ypPCdD xpPD 9E9D 9vineidth9D PAY plot@ypQCdD xpQD 9E9D 9vineidth9D PAY plot@dI dCdID vD vD 9rE9D 9vineidth9D RAY plot@dP dCdPD PBvD PBvD 9rE9D 9vineidth9D RAY plot@dQ dCdQD QBvD QBvD 9rE9D 9vineidth9D RAY xis@EHFPS HFUS HFH IFUSAY text@HFTDIFTD9t a 9 numPstr@t@iiAAAY hold offY puse@HFHIAY
end
7 gompre with wevef odeRS solutionX tmtD ymt a odeRS@9strdynfun9D H spnD uHY vHAY figure@IA hold onY puseY plot@tmtDymt@XDIAD9r9D tmtDymt@XDPAD99D tmtDymt@XDQAD9k9AY
91