Upload
man649
View
22
Download
0
Embed Size (px)
Citation preview
INTRODUCTION TO MATLAB
Dr. Derek LichtiDepartment of Spatial SciencesCurtin University of Technology
GPO Box U1987Perth, WA 6845AUSTRALIA
1
Introduction to MATLAB Derek Lichti
TABLE OF CONTENTS
TABLE OF CONTENTS............................................................................................................. 11 INTRODUCTION .................................................................................................................... 2
1.1 Background ...................................................................................................................... 21.2 Motivation ......................................................................................................................... 21.3 Document Organisation.................................................................................................... 2
2 THE MATLAB ENVIRONMENT.............................................................................................. 42.1 Starting MATLAB.............................................................................................................. 42.2 Saving and Loading a Workspace.................................................................................... 52.3 Getting Help...................................................................................................................... 52.4 Getting Help...................................................................................................................... 6
3 VARIABLES ............................................................................................................................ 73.1 Variable Definition............................................................................................................. 73.2 Variable Management ...................................................................................................... 73.3 Output Suppression.......................................................................................................... 83.4 Formatting Output............................................................................................................. 83.5 Indexing, Partitioning and Hypermatrices......................................................................... 9
4 OPERATORS AND BUILT-IN FUNCTIONS......................................................................... 104.1 Operators........................................................................................................................ 104.2 Important Built-in Functions............................................................................................ 104.3 Important Built-in Constants ........................................................................................... 11
5 M-FILES AND PROGRAMMING .......................................................................................... 125.1 Introduction..................................................................................................................... 125.2 Script and Function M-Files............................................................................................ 125.3 Some Important Programming Constructs..................................................................... 12
5.3.1 for Loop.................................................................................................................... 135.3.2 while Loop................................................................................................................ 135.3.3 if Decision Structure................................................................................................. 135.3.4 break Termination Structure .................................................................................... 135.3.5 Other Constructs...................................................................................................... 14
5.4 Program Design.............................................................................................................. 145.4.1 Documentation......................................................................................................... 145.4.2 Modularity................................................................................................................. 145.4.3 Meaningful Variable and Function Names............................................................... 145.4.4 Avoid Complicated Constructs................................................................................. 14
6 TEXT FILE INPUT AND OUTPUT........................................................................................ 156.1 Introduction..................................................................................................................... 15
6.1.1 fopen ........................................................................................................................ 156.1.2 fscanf ....................................................................................................................... 156.1.3 fprintf ........................................................................................................................ 166.1.4 fclose........................................................................................................................ 16
7 PLOTTING AND GRAPHICS................................................................................................ 177.1 Overview of Plotting Functions ....................................................................................... 17
8 A WORKED EXAMPLE ........................................................................................................ 188.1 Problem Statement......................................................................................................... 188.2 Least-Squares Solution .................................................................................................. 188.3 Solution in MATLAB........................................................................................................ 198.4 Results............................................................................................................................ 20
APPENDIX A EXAMPLE SOURCE CODE.............................................................................. 22
2
Introduction to MATLAB Derek Lichti
1 INTRODUCTION
1.1 BackgroundMATLAB is an acronym for MATrix LABoratory. It is powerful software thatallows one to perform complex scientific computations with relative ease. Examplesof complex computations that can be performed with built-in MATLAB functionsinclude as matrix inversion, singular value decomposition, Cholesky factorisation, thefast Fourier transform and many others. It is not a structured programming language,such as C or FORTRAN, though it does have programming functionality in the formof a scripting language. MATLAB also has powerful plotting and graphics functionsfor easy data display and visualisation.
MATLAB is used in several courses within the Surveying degree programme in theDepartment of Spatial Sciences. In Measurement and Adjustment Analysis, it is usedto perform least-squares adjustments of surveying network problems. Other surveyingcourses that require students to use MATLAB to solve practical problems includeSurvey Network Analysis and Design, Analytical Photogrammetry, Satellite and SpaceGeodesy, GPS Surveying and Satellite Navigation and Hydrography, to name a few.
1.2 MotivationUndeniably, there are many commercial software packages available to performnetwork adjustments. The danger in using these packages in an introductory coursesuch as Measurement and Adjustment Analysis is they can assume the role of a “blackbox” that performs the critical computations behind the scenes. To gain a clearunderstanding of the least squares adjustment process, a better approach is to “learn bydoing”, i.e., formation and solution of the relevant equations by composing one’s ownsoftware. One might argue that in this approach, a student can be overwhelmed by thedetails of multiple source code file management, debugging and, in particular,composition of matrix algebra functions such as inversion, transpose, etc. Since mostof these operations are built-in as functions, MATLAB is an excellent tool for solvingleast-squares problems. A student can learn the process of least squares withouthaving to compose matrix inversion or other functions. However, the benefits ofsoftware composition (e.g., planning a logical problem solving process) are gained incomposing MATLAB script files.
1.3 Document OrganisationThis document was not intended to serve as a definitive reference on the use ofMATLAB. On-line help or hard copy manuals are the best source to obtain theintricate details of MATLAB functions and operators. Instead, this document shouldbe regarded as only an introduction to MATLAB, as its title implies. Simpleexamples are provided throughout the document to further explain the use of operatorsor functions.
Chapter 2 provides the reader with a brief tour of the MATLAB environment andaddresses fundamental tasks like saving and loading workspaces. Chapter 3 isdevoted to variable types, definition and management within the MATLABenvironment. Chapter 4 introduces some basic MATLAB operators and some built-in
3
Introduction to MATLAB Derek Lichti
functions, such as matrix inversion. With the foundation of MATLAB operation laid,Chapter 5 is devoted to programming. Here, all the tools are put together to enable thereader to solve more complex problems such as survey network adjustment. Chapter5 introduces the fundamental unit of a MATLAB program, the M-file, describes thedifferent types of M-files and provides advice on M-file design and management. Thesyntax of various constructs, such as loops and decision structures, is also described inChapter 5. Text file input and output is the subject of Chapter 6. A brief introductionto the use of MATLAB plotting and graphics functions is given in Chapter 7. Finally,a worked example (a least-squares curve fit) that brings together the elements ofChapters 1-7 is provided in Chapter 8.
As in this chapter, text throughout this document appears in Times New Roman font.Menu options are indicated in italics. MATLAB code and commands as well as filenames appear in courier font.
4
Introduction to MATLAB Derek Lichti
2 THE MATLAB ENVIRONMENT
2.1 Starting MATLABIn the PC laboratories on the third floor of the Engineering and Surveying Building(204), MATLAB is found under Start | Mechanical | MATLAB (CHECK). Be patientwhile MATLAB is initialising, as many preliminary processes, such as environmentvariable initialisation, must be completed before you can start.
Once initialisation has completed, a window structure similar to that shown in Figure2.1 should be visible.
Figure 2.1. MATLAB Window Structure.
The MATLAB window structure shown in Figure 2.1 consists of the tool bar at thetop, the status bar at the bottom and four views, three of which are visible. TheCommand Window is the large view on the right. This is where MATLAB commandsare entered. The variable definition
x=9
is visible in the Command Window.
The Workspace view, located in the upper left portion of Figure 2.1, provides asummary of all variables currently resident in the MATLAB environment. Detailsabout the variable x are visible.
Command Window
Workspace
Command History
5
Introduction to MATLAB Derek Lichti
The Command History view (lower left) provides a list of commands previouslyentered in the Command Window. Several commands are visible, including thedefinition for x.
The fourth view, Current Directory, is not visible, only its tab can be seen below theCommand History view.
The first thing one must do is to set the working directory. This is done by clicking onthe Browse for Folder button as indicated in Figure 2.2.
Figure 2.2. Extracted Portion of the MATLAB Toolbar.
Set the working directory to d:\temp. This is the location to which all files youcreate within MATLAB will be stored. This directory is cleaned regularly, so be sureto copy all your files to a disk prior to leaving the PC lab!
2.2 Saving and Loading a WorkspaceAs will be explained in detail in Chapter 3, all variables entered by the user are storedwithin the MATLAB environment. To save the contents of your workspace, type
save filename
This command saves your workspace as a file called filename.mat. If the filename is omitted, the workspace is saved to matlab.mat.
To load a previously saved workspace, type
load filename
2.3 Getting HelpTo access MATLAB’s built-in documentation, type
help
In doing so, many possible topics will scroll past. To view each one, type
more onhelp
This will cause the first page of topics to appear, followed by the prompt
-- more --
Help Button Browse for Folder Button
6
Introduction to MATLAB Derek Lichti
Press the enter key to see the next topic or press the space bar to see the next page ofhelp topics. To turn off the controlled page output, type
more off
To get help on a specific topic, say the function inv, type
help inv
Help can also be accessed with the Help button on the tool bar, as shown in Figure2.2.
2.4 Getting HelpTo exit MATLAB, type
exit
7
Introduction to MATLAB Derek Lichti
3 VARIABLES
3.1 Variable DefinitionMATLAB permits computations with scalar, vector and matrix variables. Variablenames can be any combination of alphanumeric characters provided that the firstcharacter is a letter. Underscores are also valid characters.
Some variable definition examples are given below.• Scalar:
x = 8
• Row vector:r = [ 1 2 3 4]
• Column vector (method 1):c1 = [1 ; 2 ; 3]
• Column vector (method 2):c2 = [123 ]
• Matrix (method 1):mat_m1 = [ 1 2 3; 4 5 6 ; 7 8 9]
• Matrix (method 2)mat_m2 = [ 1 2 34 5 67 8 9 ]
• Matrix by juxtaposing vectors:mat_m3 = [ c1 c2]
• Diagonal matrixdiag_mat = diag (c1)
In the final example, the elements of the vector c1 are placed in the diagonal elementsof the square matrix using the built-in MATLAB function diag().The off-diagonalelements of diag_mat are set to zero.
Note that the semicolon indicates the start of a new matrix or vector row.
3.2 Variable ManagementTo view a list of all variables stored within the MATLAB environment, twocommands are available, who and whos. who simply provides a list of variables.whos provides more verbose output, listing the dimensions, size in bytes and class ortype for each variable.
8
Introduction to MATLAB Derek Lichti
3.3 Output SuppressionWhen a variable is defined or an operation performed in MATLAB, the resultingoutput is, by default, echoed to the Command Window. For large variables andrepeated computations, this can be unsightly and confusing. The output echo can besuppressed by ending a variable definition or operation with a semicolon (;).However, the operation is still performed and the resulting variable is stored in theMATLAB environment.
To illustrate the use of the semicolon, consider the following two examples. In eachcase, the command whos was entered after the definition of x.
1. No output suppression:
x=[ 1 ; 2 ; 3]
x =123
whosName Size Bytes Classx 3x1 24 double array
Grand total is 3 elements using 24 bytes
2. With output suppression:
x=[ 1 ; 2 ; 3];
whosName Size Bytes Classx 3x1 24 double array
Grand total is 3 elements using 24 bytes
3.4 Formatting OutputAll computations in MATLAB are performed in double floating point precision.However, the precision with which variables are displayed in the Command Windowcan be changed with the format command. Some of the relevant variations offormat are given in Table 3.1
Table 3.1. Variations of the Format Command.Command Display Format
format short Scaled fixed point format with 5 digitsformat long Scaled fixed point format with 15 digits
format short e Floating point format with 5 digitsformat long e Floating point format with 15 digitsformat short g Best of fixed or floating point format with 5 digitsformat long g Best of fixed or floating point format with 15 digits
9
Introduction to MATLAB Derek Lichti
Full details about format can be found by typing.
help format
3.5 Indexing, Partitioning and HypermatricesThere are many situations in which individual elements of a matrix or a sub-matrixmust be accessed for initialisation or extraction of results for output. This can beaccomplished in many ways, as demonstrated below. The examples refer to thevariable definitions for c1 and matrix_m1 above.
• Assignment of an individual matrix element (row 1, column 2):matrix_m1(1,2)=7
• Extraction of an individual matrix element and assignment to a new variable:variable=matrix_m1(1,2)
• Assignment of an individual vector element (element 3):c1(3)=11
• Extraction of a sub-matrix (rows 1-2, columns 1-2):sub_mat=matrix_m1(1:2,1:2)
• Extraction of a column vector from a matrix (column 2):col_vect=matrix_m1(:,2)
• Extraction of a row vector from a matrix (row 2):row_vect=matrix_m1(2,:)
Notes:• A comma is used to separate indices for multidimensional variables (e.g.,
matrices).• A colon is used to indicate a range of elements. If used on its own, the colon
refers to all elements of that dimension. A subset of elements are specified bynumerical limits on either side of the colon (e.g., start:end).
10
Introduction to MATLAB Derek Lichti
4 OPERATORS AND BUILT-IN FUNCTIONS
4.1 OperatorsSome of the most important MATLAB operators are summarised with examples inTable 4.1. Where appropriate, they can be used with scalars, vectors and matrices.
Table 4.1. Some MATLAB Operators.Operation MATLAB Operator ExampleAddition + c=a+b
Subtraction - c=a-b
Matrix Multiplication * c=a*b
Matrix Power ^ c=a^2
Transpose ‘ a_trans=a’
Array Multiplication .* c=a.*b
Logical Equal == a == b
Array multiplication differs from matrix multiplication in that corresponding elementsof a and b are multiplied, rather than following the normal rule. To illustrate thedifference, consider the following example, in which the matrix a is defined andmultiplied by itself using both matrix and array multiplication.
a=[1 2; 3 4]
a =1 23 4
a*aans =
7 1015 22
a.*aans =
1 49 16
4.2 Important Built-in FunctionsSome of the important built-in MATLAB functions for matrix operations are givenwith examples in Table 4.2. A comprehensive list can be obtained by typing
help matfun
11
Introduction to MATLAB Derek Lichti
Table 4.2. Some MATLAB Built-In Matrix Functions.Operation MATLAB Function Example
Matrix Inversion inv a_inv=inv(a)
Matrix Determinant det det_a=det(a)
Create Diagonal Matrix1 diag a=diag(b)
Extract Diagonal Matrix2 diag b=diag(a)
Create Identity Matrix3 eye I=eye(3)
Create Null Matrix4 zeros z_3x4=zeros(3,4)
Create A Matrix of Ones5 .* o_2x3=ones(2,3)
Pseudoinverse pinv a_pinv=pinv(a)
Size of Matrix size [m,n]=size(mat)
1 b is the vector of elements assigned to the diagonal of the resulting matrix a.2 b is the resulting vector of elements extracted from the diagonal of matrix a.3 A 3x3 identity matrix is created in the example.4 A 3x4 null matrix is created in the example.5 A 2x3 matrix with all elements equal to one is created in the example.
Table 4.3 lists some of the elementary mathematical functions defined in MATLAB.A comprehensive list can be found by typing
help elfun
Table 4.3. Some MATLAB Built-In Elementary Functions.Function MATLAB syntax
absolute value abs(x)
minimum value, maximum value min(x), max(x)
sort values sort(x)
sine, cosine, tangent sin(x), cos(x), tan(x)
inverse sine, cosine, tangent asin(x), acos(x), atan(x)
inverse tangent (two arguments) atan2(x,y)
exponential exp(x)
natural logarithm log(x)
square root sqrt(x)
round to nearest integer round(x)
4.3 Important Built-in ConstantsPerhaps the most important built-in constant is π, defined in MATLAB as pi.
12
Introduction to MATLAB Derek Lichti
5 M-FILES AND PROGRAMMING
5.1 IntroductionAn M-file is an external text file comprised of variable definitions and function thatMATLAB reads, interprets and executes. An M-file is ideal for performing longinstruction sets as it precludes the need for manual re-entry of commands. M-files arevery useful for constructing programs to solve least-squares problems.
M-files can be composed with the MATLAB Editor/Debugger (File | New | M-file).All M-files have the extension .m. For easy access, they can be located in the samedirectory as your workspace.
5.2 Script and Function M-FilesA script M-file is a set of instructions. All variables defined within a script M-file areglobal in the sense that they reside in the MATLAB environment. The instructionswithin a script file are invoked by entering the filename (without the .m extension)from the MATLAB environment or from another M-file.
A function M-file is also a set of instructions, but is used like a built-in MATLABfunction. That is, a function file can accept parameters and can produce return values.The critical syntax for a function M-file appears in the first line of the file. Forexample,
function [u,v]=my_func(x,y)
The keyword function indicates that the file is a function M-file (the file name ismy_func.m). The function, my_func, accepts two arguments or parameters, x andy, and returns two output values, u and v. Any number of parameters and returnvalues are possible, and both may be scalars, vectors or matrices. The syntax to callthis function, either from the MATLAB environment or from another M-file, is
[u,v]=my_func(x,y)
Though the variable names in the function call match those in the function definition,they have different scope. Apart from the return values, function M-file variableshave local scope. That is, any variables defined within the file (e.g., parameters andvariables for intermediate computations) are not visible in the MATLAB environmentor M-file from which the function was called. Only the return values can be accessedby MATLAB (or calling M-file). Return value variables must be explicitly definedwithin the function M-file.
Examples of both script and function M-files are given in Appendix A.
5.3 Some Important Programming ConstructsMATLAB possesses several built-in programming constructs, including keywords forloop and decision structures. All may be imbedded within M-files or entered directly
13
Introduction to MATLAB Derek Lichti
into the MATLAB environment. Examples of some of the most pertinent constructsare given below.
5.3.1 for LoopThe for loop allows repeated computation a fixed number of times. In the examplebelow, j is the index variable that is incremented from 1 to n (predefined as 10). Theelements of the vector x are sequentially accessed each iteration. As with mostMATLAB programming constructs, the for loop is terminated with the endkeyword.
n=10;x=zeros(n);for j=1:n
x(j)=j*10;end
5.3.2 while LoopThe while construct also allows repeated computation, but does so only once atermination criterion has been satisfied. To illustrate, consider the example below, inwhich the loop executes until c≥10.
c=0;while c >= 10
c=c+1;end
5.3.3 if Decision StructureThe sytntax for the if decision construct is illustrated by the example below.
if x == 10y=5;
else if x > 10y=4;
elsey=3;
end
5.3.4 break Termination StructureThe break keyword terminates execution of for and while loops. The syntax isillustrated below by example. When the break statement is reached, programcontrol jumps out of the for loop.
for j=1:10if j > 5
breakend
end
Note the use of semicolons in each example. Semicolons are not usually placed at theend of for, while, if, else if, else or end statements.
14
Introduction to MATLAB Derek Lichti
5.3.5 Other ConstructsOther important programming constructs, such as switch, and functions can befound by typing
help lang
5.4 Program DesignSome of the elements of good program design are outlined in the followingsubsections. Adherence to these guidelines will make program organisation andcomposition easier, streamline debugging, allow easier addition of extra sub-routinesand make the code more readable by others.
5.4.1 DocumentationDocumentation (commenting) of source code is not merely an academic exercise. It isdesigned to indicate the code composer, provide a revision history, explain thepurpose of the code and explain how the code functions. Good documentation makescode more readable and easier to debug. As a general guide, someone who had noinput into the code composition should be able to follow the program flow on thebasis of the documentation. Comment lines in MATLAB begin with the per cent (%)character. For example,
% this entire line is a comment
Examples of well-documented M-files are found in Appendix A.
5.4.2 ModularityLarge MATLAB programs should not be composed such that all variable definitionsand commands appear in one long, obfuscated file. Blocks of code that performdifferent functions (i.e., sub-routines) should be placed in separate function M-files.This measure makes the code more readable and easier to debug. See Appendix A foran example of a modular program.
5.4.3 Meaningful Variable and Function NamesVariables and functions should be given descriptive names so that someone adding toor debugging source code can readily understand their purpose. Some variables, suchas loop counters, can be given single character names (i.e., c, j, etc.). In general,though, single character names should be avoided.
5.4.4 Avoid Complicated ConstructsOne of the best pieces of advice a programmer can accept is to keep it simple.Construction of complicated constructs to perform a set of computations in ten linesrather than twenty is indeed impressive. However, the readability and “debugability”of such code must be considered. Bugs are more difficult to locate in complex codethan in simple, clearly laid-out code.
15
Introduction to MATLAB Derek Lichti
6 TEXT FILE INPUT AND OUTPUT
6.1 IntroductionMATLAB has several built-in functions that facilitate input and output of data fromboth binary and text files. Use of these functions removes the need to hard-code datainto M-files and awkward cutting and pasting of data from other applications into theMATLAB environment. An overview of a few important functions is given in thefollowing sub-sections. Examples showing the use of some of the functions are foundin Appendix A.
6.1.1 fopenThe fopen function must be used before reading from or writing to a file. Thesyntax is given by
fid=fopen(filename,permission)
This function call opens the file indicated by the text string filename. Thepermission argument indicates both the type of file (i.e, text or binary) and modein which it is to be opened (i.e., for reading or writing). Table 7.1 gives a list of someof the permission strings. Others can be found by typing
help fopen
Table 7.1. File Open Permission StringsPermission String Mode
‘r’ Read from a binary file‘rt Read from a text file‘w’ Write to a binary file (creates the file if nonexistant; erases all
contents if file already exists)‘wt’ Write to a text file
The return value, fid, is the handle to the file. It is integer-valued and if the file openoperation was successful, is positive-valued. If fopen was unsuccessful, fid isequal to -1.
6.1.2 fscanfThe function fscanf is used to read data from a text file. (fread is used to readfrom a binary file.) The general syntax is
[a,count]=fscanf(fid,format,size)
The fid parameter is the handle to a previously opened text file. format instructsMATLAB what type of data is to be read from the file and is a text string made up ofconversion specifiers similar to those of the C programming language. Someexamples are given in Table 7.2. Others can be found by typing
help fscanf
16
Introduction to MATLAB Derek Lichti
Table 7.2. Conversion Specifiers.Conversion Specifier Data Type Read
‘%f’ Floating point‘%d’ Integer‘%u’ Unsigned integer
The optional size argument tells MATLAB how many elements of type specified byformat to read into the variable a. Possible entries are indicated in Table 7.3. Ifsize is omitted, then fscanf reads the contents of the entire file.
Table 7.3. Possible Size Entries.Entry FunctionN Read at most N elements into a column vector.Inf Read at most to the end of the file.[M,N] Read at most M * N elements filling at least an M-by-N matrix, in
column order. N can be inf, but not M.
The return value count is useful for error checking as it indicates the number ofelements successfully read into the variable a.
6.1.3 fprintfThe function fprintf is used to write data to a text file. (fwrite is used to writedata to a binary file.) The general syntax is
count=fprintf(fid,format,a…)
The fid and format arguments are as in fscanf. fprintf can take a variablenumber of arguments to print as indicated by the ellipsis (…) after the first variable, a.The return value count indicates the number of elements successfully written to thefile.
6.1.4 fcloseWhen finished reading from or writing to a file, the stream is closed using fclose,for which the syntax is
st=fclose(fid)
The st return value is set to 0 if successful and –1 if the file pointed to by fid couldnot be closed. Failure usually indicates the file is already closed.
17
Introduction to MATLAB Derek Lichti
7 PLOTTING AND GRAPHICS
7.1 Overview of Plotting FunctionsMATLAB has many graphics and plotting tools available to represent data. Use ofthese is very helpful for visualising data from, for example, a least-squaresadjustment. An example showing the use of the plot command is given inAppendix A. Some of the more relevant plotting functions are reviewed here. Detailsof each can be found in MATLAB help.
• 2-D plot of x and y dataplot(x,y)
• 3-D plot of x, y and z dataplot(x,y,z)
• Display of a digital image (each element of the matrix c specifies the colour of anindividual pixel)
image(c)
18
Introduction to MATLAB Derek Lichti
8 A WORKED EXAMPLE
8.1 Problem StatementEstimation of the coefficients of a polynomial that optimally fits a set of pointobservations is a classic problem for which the least-squares method is utilised. As anexample, consider the set of point observations (x and y co-ordinates) listed in Table8.1.
Table 8.1. Observed Point Co-ordinates.i xi yi1 0 4.262 1.5 4.583 2 4.334 4 1.455 5.2 -1.61
Required is a parabola that best fits these data points. Given that a parabola can beparameterised as
y a a x a xi i i= + +0 1 22 , (8.1)
the problem boils down to determination of the coefficients a0, a1 and a2. Since thereare more observations, 5, than unknowns, 3, this is an over-determined problem,which is highly desirable for least-squares estimation. In this problem, the x co-ordinates are considered as constants and the y co-ordinates are treated as theobservations.
8.2 Least-Squares SolutionThe least-squares solution begins with formation of a system of observation equationshaving the form
Ax w r+ = , (8.2)
where A is the design matrix, x is the parameter vector, w is the misclosure vector,and r is the residual vector. The design matrix reflects the geometry of the problem,the parameter vector consists of the unknown parabola coefficients, the misclosurevector, in this case, is comprised of the observed y co-ordinates, and the elements ofthe residual vector represent the deviations of the data points from the best-fitparabola. The parameter and residual vectors are estimable quantities.
The formation and solution of Equation 8.2 is the core subject of Measurement andAdjustment Analysis. Neglecting for the moment the processes behind its formation,the form of this equation is given by
19
Introduction to MATLAB Derek Lichti
11111
1 12
2 22
3 32
4 42
5 52
0
1
2
1
2
3
4
5
1
2
3
4
5
x xx xx xx xx x
aaa
yyyyy
rrrrr
�
�
������
�
�
������
�
�
���
�
�
���
+
−−−−−
�
�
������
�
�
������
=
�
�
������
�
�
������
(8.3)1 0 01 15 2 251 2 41 4 161 5 2 27 04
4 264 584 22145
161
0
1
2
1
2
3
4
5
. .
. .
.
.
.
..
�
�
������
�
�
������
�
�
���
�
�
���
+
−−−−
�
�
������
�
�
������
=
�
�
������
�
�
������
aaa
rrrrr
The least-squares solution is given (without proof) by
( )x A A A wT T= −−1
. (8.4)
Some other quantities of interest are the residual vector, r, computed via Equation 8.2,and the estimated variance factor, σ 0
2 , given by
σ 02 =
−r r
n u
T
(8.5)
where n is the number of observations (5) and u the number of unknowns (3).
8.3 Solution in MATLABThe MATLAB solution to the parabola fit problem has been formulated in a modularfashion. That is, each major task, such as file input, least-squares solution, etc., islocated in a separate function M-file that is called by a main script M-file. Theorganisation is depicted in Table 8.2.
Table 8.2. MATLAB M-File Organisation.M-File Role
example.m main script filemy_input.m file input of point dataform_eq.m form observation equationssolution.m least squares solutionmy_output.m formatted output of resultsmy_plot.m plotting of results
The source code for each file is given in Appendix A. The comments explain thefunction of each block of code. Note the documentation at the top of each M-file toindicate the purpose, arguments, return values, author and creation date. Read throughthe code carefully to become familiar with the style and good programming practise.
20
Introduction to MATLAB Derek Lichti
The input data (the last two columns of Table 8.1) were contained within a text filecalled data.txt, the contents of which are shown below.
0 4.261.5 4.582 4.334 1.455.2 -1.61
8.4 ResultsThe formatted output, written to file data.out, is given below.
A matrix1.0000 0.0000 0.00001.0000 1.5000 2.25001.0000 2.0000 4.00001.0000 4.0000 16.00001.0000 5.2000 27.0400
w vector-4.2600-4.5800-4.3300-1.45001.6100
solution vector4.26620.7486
-0.3617
residual vector0.0062
-0.0047-0.01340.0234
-0.0115
variance factor 0.0005
The MATLAB plot of the data points and best-fit parabola is shown in Figure 8.1.
21
Introduction to MATLAB Derek Lichti
-1 0 1 2 3 4 5 6-5
-4
-3
-2
-1
0
1
2
3
4
5
Figure 8.1. Observed Data Points and Best-Fit Parabola.
22
Introduction to MATLAB Derek Lichti
APPENDIX A EXAMPLE SOURCE CODE
% example.m% purpose: main script file for the least squares solution% of the best fit parabola example% Derek Lichti% 28 August 2001
% read input data from file[x,y]=my_input('data.txt');
% check for file open error and for minmum number of observations (3)if (size(x) < 1)
breakend
% form observation equations[A,w]=form_eq(x,y);
% least squares solution[sol_vect,resid,vf]=ls_solution(A,w);
% file output of resultsmy_output(A,w,sol_vect,resid,vf,'data.out');
% plotting of resultsmy_plot(x,y,sol_vect);
% ***end of file***
23
Introduction to MATLAB Derek Lichti
function [x,y]=my_input(filename)% my_input.m% reads x and y co-ordinates from a text file given the file name% and extension% arguments:% filename% return values:% x vector of x co-ordinates% y vector of y co-ordinates% both are null vectors if file open fails% Derek Lichti% 28 August 2001
% open file in text read modefid=fopen(filename,'rt');
% check fid for success of file open request% note use of logical equal operator ==if (fid == -1)
x=0;y=0;return
end
% read data using a temporary variable% [2,inf] tells MATLAB that there are 2 fields but an unknown% number of entries% %f tells MATLAB that the input data are floating point numberstemp= fscanf(fid,'%f',[2,inf]);
% transpose and divide temporary matrix into x and ytemp=temp';
% this assigns all elements the first column to xx=temp(:,1);% this assigns all elements the second column to yy=temp(:,2);
% close file--very importantfclose(fid);
% ***end of file***
24
Introduction to MATLAB Derek Lichti
function [A,w]=form_eq(x,y)% form_eq.m% given the x and y co-ordinates, the A and w matrices are formed% arguments:% x vector of x co-ordinates% y vector of y co-ordinates% return values:% A the design matrix% w the misclosure vector% Derek Lichti% 23 October 2001
% determine the number of pointsn=max(size(x));
% allocate memoryA=zeros(n,3);w=zeros(n,1);
% form A and wfor i=1:n
A(i,1)=1;A(i,2)=x(i);A(i,3)=x(i)^2;
w(i)=-y(i);end
% ***end of file***
25
Introduction to MATLAB Derek Lichti
function [sol_vect,resid,var_fact]=ls_solution(A,w)% ls_solution.m% given the A and w matrices, various least squares solution% quantities are calculated% arguments:% A the design matrix% w the misclosure vector% return values:% sol_vect the solution vector (x)% resid the residual vector% var_fact the variance factor% Derek Lichti% 23 October 2001
% calc solution vectorsol_vect=-inv(A'*A)*A'*w;
% residual vectorresid=A*sol_vect+w;
% calc n and u from dimensions of A[n,u]=size(A);
var_fact=resid'*resid/(n-u);
% ***end of file***
26
Introduction to MATLAB Derek Lichti
function my_output(A,w,sol_vect,resid,vf,filename);% my_output.m% function to write least squares output to filename% arguments% A the design matrix% w the misclosure vector% sol_vect the LS solution vector% resid the residual vector% vf the variance factor% filename the output filename with extension% return values% none% Derek Lichti% 23 October 2001
% open file in text write modefid=fopen(filename,'wt');
% check fid for success of file open request% note use of logical equal operator ==if (fid == -1)
returnend
% determine n and u from A[n,u]=size(A);
% write output with specified precision
% A matrix--note use of field width and precision valuesfprintf(fid,'A matrix\n');for i=1:n
for j=1:ufprintf(fid,'%8.4f',A(i,j));
endfprintf(fid,'\n');
end
% other quantitiesfprintf(fid,'\nw vector\n');for i=1:n
fprintf(fid,'%8.4f\n',w(i));end
fprintf(fid,'\nsolution vector\n');for i=1:u
fprintf(fid,'%8.4f\n',sol_vect(i));end
fprintf(fid,'\nresidual vector\n');for i=1:n
fprintf(fid,'%8.4f\n',resid(i));end
fprintf(fid,'\nvariance factor %8.4f', vf);
% close filefclose(fid);
% ***end of file***
27
Introduction to MATLAB Derek Lichti
function my_plot(x,y,sol_vect);% my_plot.m% function to plot observed data points and best fit curve% arguments% x,y the observed point coordinates% sol_vect the LS solution vector% return values% none% Derek Lichti% 23 October 2001
% plot observed data as discrete points (diamonds)plot(x,y,'d');
% this allows two series to plotted on the same graphhold on
% plot curve from -1 to 6 with 100 linearly spaced valuesx_curve=linspace(-1,6);
% calc curve from solution vectorn=max(size(x_curve));y_curve=zeros(n,1);for i=1:n
y_curve(i)=sol_vect(1)+sol_vect(2)*x_curve(i)+sol_vect(3)*x_curve(i)^2;end
plot(x_curve,y_curve);
hold off
% ***end of file***