Вы находитесь на странице: 1из 28

INTRODUCTION TO MATLAB

Dr. Derek Lichti


Department of Spatial Sciences
Curtin University of Technology
GPO Box U1987
Perth, WA 6845
AUSTRALIA
1

TABLE OF CONTENTS

TABLE OF CONTENTS............................................................................................................. 1
1 INTRODUCTION .................................................................................................................... 2
1.1 Background ...................................................................................................................... 2
1.2 Motivation ......................................................................................................................... 2
1.3 Document Organisation.................................................................................................... 2
2 THE MATLAB ENVIRONMENT .............................................................................................. 4
2.1 Starting MATLAB.............................................................................................................. 4
2.2 Saving and Loading a Workspace.................................................................................... 5
2.3 Getting Help...................................................................................................................... 5
2.4 Getting Help...................................................................................................................... 6
3 VARIABLES ............................................................................................................................ 7
3.1 Variable Definition............................................................................................................. 7
3.2 Variable Management ...................................................................................................... 7
3.3 Output Suppression.......................................................................................................... 8
3.4 Formatting Output............................................................................................................. 8
3.5 Indexing, Partitioning and Hypermatrices ......................................................................... 9
4 OPERATORS AND BUILT-IN FUNCTIONS......................................................................... 10
4.1 Operators........................................................................................................................ 10
4.2 Important Built-in Functions............................................................................................ 10
4.3 Important Built-in Constants ........................................................................................... 11
5 M-FILES AND PROGRAMMING .......................................................................................... 12
5.1 Introduction..................................................................................................................... 12
5.2 Script and Function M-Files............................................................................................ 12
5.3 Some Important Programming Constructs..................................................................... 12
5.3.1 for Loop.................................................................................................................... 13
5.3.2 while Loop................................................................................................................ 13
5.3.3 if Decision Structure................................................................................................. 13
5.3.4 break Termination Structure .................................................................................... 13
5.3.5 Other Constructs...................................................................................................... 14
5.4 Program Design.............................................................................................................. 14
5.4.1 Documentation......................................................................................................... 14
5.4.2 Modularity................................................................................................................. 14
5.4.3 Meaningful Variable and Function Names ............................................................... 14
5.4.4 Avoid Complicated Constructs................................................................................. 14
6 TEXT FILE INPUT AND OUTPUT ........................................................................................ 15
6.1 Introduction..................................................................................................................... 15
6.1.1 fopen ........................................................................................................................ 15
6.1.2 fscanf ....................................................................................................................... 15
6.1.3 fprintf ........................................................................................................................ 16
6.1.4 fclose........................................................................................................................ 16
7 PLOTTING AND GRAPHICS................................................................................................ 17
7.1 Overview of Plotting Functions ....................................................................................... 17
8 A WORKED EXAMPLE ........................................................................................................ 18
8.1 Problem Statement......................................................................................................... 18
8.2 Least-Squares Solution .................................................................................................. 18
8.3 Solution in MATLAB........................................................................................................ 19
8.4 Results............................................................................................................................ 20
APPENDIX A EXAMPLE SOURCE CODE.............................................................................. 22

Introduction to MATLAB Derek Lichti


2

1 INTRODUCTION

1.1 Background
MATLAB is an acronym for MATrix LABoratory. It is powerful software that
allows one to perform complex scientific computations with relative ease. Examples
of complex computations that can be performed with built-in MATLAB functions
include as matrix inversion, singular value decomposition, Cholesky factorisation, the
fast 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 form
of a scripting language. MATLAB also has powerful plotting and graphics functions
for easy data display and visualisation.

MATLAB is used in several courses within the Surveying degree programme in the
Department of Spatial Sciences. In Measurement and Adjustment Analysis, it is used
to perform least-squares adjustments of surveying network problems. Other surveying
courses that require students to use MATLAB to solve practical problems include
Survey Network Analysis and Design, Analytical Photogrammetry, Satellite and Space
Geodesy, GPS Surveying and Satellite Navigation and Hydrography, to name a few.

1.2 Motivation
Undeniably, there are many commercial software packages available to perform
network adjustments. The danger in using these packages in an introductory course
such as Measurement and Adjustment Analysis is they can assume the role of a “black
box” that performs the critical computations behind the scenes. To gain a clear
understanding of the least squares adjustment process, a better approach is to “learn by
doing”, i.e., formation and solution of the relevant equations by composing one’s own
software. One might argue that in this approach, a student can be overwhelmed by the
details of multiple source code file management, debugging and, in particular,
composition of matrix algebra functions such as inversion, transpose, etc. Since most
of these operations are built-in as functions, MATLAB is an excellent tool for solving
least-squares problems. A student can learn the process of least squares without
having to compose matrix inversion or other functions. However, the benefits of
software composition (e.g., planning a logical problem solving process) are gained in
composing MATLAB script files.

1.3 Document Organisation


This document was not intended to serve as a definitive reference on the use of
MATLAB. On-line help or hard copy manuals are the best source to obtain the
intricate details of MATLAB functions and operators. Instead, this document should
be regarded as only an introduction to MATLAB, as its title implies. Simple
examples are provided throughout the document to further explain the use of operators
or functions.

Chapter 2 provides the reader with a brief tour of the MATLAB environment and
addresses fundamental tasks like saving and loading workspaces. Chapter 3 is
devoted to variable types, definition and management within the MATLAB
environment. Chapter 4 introduces some basic MATLAB operators and some built-in

Introduction to MATLAB Derek Lichti


3

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 the
reader to solve more complex problems such as survey network adjustment. Chapter
5 introduces the fundamental unit of a MATLAB program, the M-file, describes the
different types of M-files and provides advice on M-file design and management. The
syntax of various constructs, such as loops and decision structures, is also described in
Chapter 5. Text file input and output is the subject of Chapter 6. A brief introduction
to 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 of
Chapters 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 file
names appear in courier font.

Introduction to MATLAB Derek Lichti


4

2 THE MATLAB ENVIRONMENT

2.1 Starting MATLAB


In the PC laboratories on the third floor of the Engineering and Surveying Building
(204), MATLAB is found under Start | Mechanical | MATLAB (CHECK). Be patient
while MATLAB is initialising, as many preliminary processes, such as environment
variable initialisation, must be completed before you can start.

Once initialisation has completed, a window structure similar to that shown in Figure
2.1 should be visible.

Workspace

Command Window

Command History

Figure 2.1. MATLAB Window Structure.

The MATLAB window structure shown in Figure 2.1 consists of the tool bar at the
top, the status bar at the bottom and four views, three of which are visible. The
Command Window is the large view on the right. This is where MATLAB commands
are 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 a
summary of all variables currently resident in the MATLAB environment. Details
about the variable x are visible.

Introduction to MATLAB Derek Lichti


5

The Command History view (lower left) provides a list of commands previously
entered in the Command Window. Several commands are visible, including the
definition for x.

The fourth view, Current Directory, is not visible, only its tab can be seen below the
Command History view.

The first thing one must do is to set the working directory. This is done by clicking on
the Browse for Folder button as indicated in Figure 2.2.

Figure 2.2. Extracted Portion of


Help Button the MATLAB
Browse Toolbar.
for Folder Button

Set the working directory to d:\temp. This is the location to which all files you
create within MATLAB will be stored. This directory is cleaned regularly, so be sure
to copy all your files to a disk prior to leaving the PC lab!

2.2 Saving and Loading a Workspace


As will be explained in detail in Chapter 3, all variables entered by the user are stored
within 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 file
name is omitted, the workspace is saved to matlab.mat.

To load a previously saved workspace, type

load filename

2.3 Getting Help


To access MATLAB’s built-in documentation, type

help

In doing so, many possible topics will scroll past. To view each one, type

more on
help

This will cause the first page of topics to appear, followed by the prompt

-- more --

Introduction to MATLAB Derek Lichti


6

Press the enter key to see the next topic or press the space bar to see the next page of
help 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 Figure
2.2.

2.4 Getting Help


To exit MATLAB, type

exit

Introduction to MATLAB Derek Lichti


7

3 VARIABLES

3.1 Variable Definition


MATLAB permits computations with scalar, vector and matrix variables. Variable
names can be any combination of alphanumeric characters provided that the first
character 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 = [1
2
3 ]

• Matrix (method 1):


mat_m1 = [ 1 2 3; 4 5 6 ; 7 8 9]

• Matrix (method 2)
mat_m2 = [ 1 2 3
4 5 6
7 8 9 ]

• Matrix by juxtaposing vectors:


mat_m3 = [ c1 c2]

• Diagonal matrix
diag_mat = diag (c1)

In the final example, the elements of the vector c1 are placed in the diagonal elements
of the square matrix using the built-in MATLAB function diag().The off-diagonal
elements of diag_mat are set to zero.

Note that the semicolon indicates the start of a new matrix or vector row.

3.2 Variable Management


To view a list of all variables stored within the MATLAB environment, two
commands 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 or
type for each variable.

Introduction to MATLAB Derek Lichti


8

3.3 Output Suppression


When a variable is defined or an operation performed in MATLAB, the resulting
output is, by default, echoed to the Command Window. For large variables and
repeated computations, this can be unsightly and confusing. The output echo can be
suppressed by ending a variable definition or operation with a semicolon (;).
However, the operation is still performed and the resulting variable is stored in the
MATLAB environment.

To illustrate the use of the semicolon, consider the following two examples. In each
case, the command whos was entered after the definition of x.

1. No output suppression:

x=[ 1 ; 2 ; 3]

x =
1
2
3

whos
Name Size Bytes Class
x 3x1 24 double array
Grand total is 3 elements using 24 bytes

2. With output suppression:

x=[ 1 ; 2 ; 3];

whos
Name Size Bytes Class
x 3x1 24 double array
Grand total is 3 elements using 24 bytes

3.4 Formatting Output


All computations in MATLAB are performed in double floating point precision.
However, the precision with which variables are displayed in the Command Window
can be changed with the format command. Some of the relevant variations of
format 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 digits
format long Scaled fixed point format with 15 digits
format short e Floating point format with 5 digits
format long e Floating point format with 15 digits
format short g Best of fixed or floating point format with 5 digits
format long g Best of fixed or floating point format with 15 digits

Introduction to MATLAB Derek Lichti


9

Full details about format can be found by typing.

help format

3.5 Indexing, Partitioning and Hypermatrices


There are many situations in which individual elements of a matrix or a sub-matrix
must be accessed for initialisation or extraction of results for output. This can be
accomplished in many ways, as demonstrated below. The examples refer to the
variable 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 by
numerical limits on either side of the colon (e.g., start:end).

Introduction to MATLAB Derek Lichti


10

4 OPERATORS AND BUILT-IN FUNCTIONS

4.1 Operators
Some of the most important MATLAB operators are summarised with examples in
Table 4.1. Where appropriate, they can be used with scalars, vectors and matrices.

Table 4.1. Some MATLAB Operators.


Operation MATLAB Operator Example
Addition + 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 elements


of a and b are multiplied, rather than following the normal rule. To illustrate the
difference, consider the following example, in which the matrix a is defined and
multiplied by itself using both matrix and array multiplication.

a=[1 2; 3 4]

a =
1 2
3 4

a*a
ans =
7 10
15 22

a.*a
ans =
1 4
9 16

4.2 Important Built-in Functions


Some of the important built-in MATLAB functions for matrix operations are given
with examples in Table 4.2. A comprehensive list can be obtained by typing

help matfun

Introduction to MATLAB Derek Lichti


11

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)
1 diag a=diag(b)
Create Diagonal Matrix
2 diag b=diag(a)
Extract Diagonal Matrix
3 eye I=eye(3)
Create Identity Matrix
4 zeros z_3x4=zeros(3,4)
Create Null Matrix
5 .* o_2x3=ones(2,3)
Create A Matrix of Ones
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 Constants


Perhaps the most important built-in constant is π, defined in MATLAB as pi.

Introduction to MATLAB Derek Lichti


12

5 M-FILES AND PROGRAMMING

5.1 Introduction
An M-file is an external text file comprised of variable definitions and function that
MATLAB reads, interprets and executes. An M-file is ideal for performing long
instruction sets as it precludes the need for manual re-entry of commands. M-files are
very 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 same
directory as your workspace.

5.2 Script and Function M-Files


A script M-file is a set of instructions. All variables defined within a script M-file are
global in the sense that they reside in the MATLAB environment. The instructions
within 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 MATLAB
function. 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. For
example,

function [u,v]=my_func(x,y)

The keyword function indicates that the file is a function M-file (the file name is
my_func.m). The function, my_func, accepts two arguments or parameters, x and
y, and returns two output values, u and v. Any number of parameters and return
values are possible, and both may be scalars, vectors or matrices. The syntax to call
this 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 variables
have local scope. That is, any variables defined within the file (e.g., parameters and
variables for intermediate computations) are not visible in the MATLAB environment
or M-file from which the function was called. Only the return values can be accessed
by MATLAB (or calling M-file). Return value variables must be explicitly defined
within the function M-file.

Examples of both script and function M-files are given in Appendix A.

5.3 Some Important Programming Constructs


MATLAB possesses several built-in programming constructs, including keywords for
loop and decision structures. All may be imbedded within M-files or entered directly

Introduction to MATLAB Derek Lichti


13

into the MATLAB environment. Examples of some of the most pertinent constructs
are given below.

5.3.1 for Loop


The for loop allows repeated computation a fixed number of times. In the example
below, j is the index variable that is incremented from 1 to n (predefined as 10). The
elements of the vector x are sequentially accessed each iteration. As with most
MATLAB programming constructs, the for loop is terminated with the end
keyword.

n=10;
x=zeros(n);
for j=1:n
x(j)=j*10;
end

5.3.2 while Loop


The while construct also allows repeated computation, but does so only once a
termination criterion has been satisfied. To illustrate, consider the example below, in
which the loop executes until c≥10.

c=0;
while c >= 10
c=c+1;
end

5.3.3 if Decision Structure


The sytntax for the if decision construct is illustrated by the example below.

if x == 10
y=5;
else if x > 10
y=4;
else
y=3;
end

5.3.4 break Termination Structure


The break keyword terminates execution of for and while loops. The syntax is
illustrated below by example. When the break statement is reached, program
control jumps out of the for loop.

for j=1:10
if j > 5
break
end
end

Note the use of semicolons in each example. Semicolons are not usually placed at the
end of for, while, if, else if, else or end statements.

Introduction to MATLAB Derek Lichti


14

5.3.5 Other Constructs


Other important programming constructs, such as switch, and functions can be
found by typing

help lang

5.4 Program Design


Some of the elements of good program design are outlined in the following
subsections. Adherence to these guidelines will make program organisation and
composition easier, streamline debugging, allow easier addition of extra sub-routines
and make the code more readable by others.

5.4.1 Documentation
Documentation (commenting) of source code is not merely an academic exercise. It is
designed to indicate the code composer, provide a revision history, explain the
purpose of the code and explain how the code functions. Good documentation makes
code more readable and easier to debug. As a general guide, someone who had no
input into the code composition should be able to follow the program flow on the
basis 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 Modularity
Large MATLAB programs should not be composed such that all variable definitions
and commands appear in one long, obfuscated file. Blocks of code that perform
different 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 for
an example of a modular program.

5.4.3 Meaningful Variable and Function Names


Variables and functions should be given descriptive names so that someone adding to
or debugging source code can readily understand their purpose. Some variables, such
as 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 Constructs


One 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 lines
rather than twenty is indeed impressive. However, the readability and “debugability”
of such code must be considered. Bugs are more difficult to locate in complex code
than in simple, clearly laid-out code.

Introduction to MATLAB Derek Lichti


15

6 TEXT FILE INPUT AND OUTPUT

6.1 Introduction
MATLAB has several built-in functions that facilitate input and output of data from
both binary and text files. Use of these functions removes the need to hard-code data
into M-files and awkward cutting and pasting of data from other applications into the
MATLAB environment. An overview of a few important functions is given in the
following sub-sections. Examples showing the use of some of the functions are found
in Appendix A.

6.1.1 fopen
The fopen function must be used before reading from or writing to a file. The
syntax is given by

fid=fopen(filename,permission)

This function call opens the file indicated by the text string filename. The
permission argument indicates both the type of file (i.e, text or binary) and mode
in which it is to be opened (i.e., for reading or writing). Table 7.1 gives a list of some
of the permission strings. Others can be found by typing

help fopen

Table 7.1. File Open Permission Strings


Permission 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 open
operation was successful, is positive-valued. If fopen was unsuccessful, fid is
equal to -1.

6.1.2 fscanf
The function fscanf is used to read data from a text file. (fread is used to read
from 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 instructs
MATLAB what type of data is to be read from the file and is a text string made up of
conversion specifiers similar to those of the C programming language. Some
examples are given in Table 7.2. Others can be found by typing

help fscanf

Introduction to MATLAB Derek Lichti


16

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 by
format to read into the variable a. Possible entries are indicated in Table 7.3. If
size is omitted, then fscanf reads the contents of the entire file.

Table 7.3. Possible Size Entries.


Entry Function
N 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 of
elements successfully read into the variable a.

6.1.3 fprintf
The function fprintf is used to write data to a text file. (fwrite is used to write
data 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 variable
number 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 the
file.

6.1.4 fclose
When 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 could
not be closed. Failure usually indicates the file is already closed.

Introduction to MATLAB Derek Lichti


17

7 PLOTTING AND GRAPHICS

7.1 Overview of Plotting Functions


MATLAB has many graphics and plotting tools available to represent data. Use of
these is very helpful for visualising data from, for example, a least-squares
adjustment. An example showing the use of the plot command is given in
Appendix A. Some of the more relevant plotting functions are reviewed here. Details
of each can be found in MATLAB help.

• 2-D plot of x and y data


plot(x,y)

• 3-D plot of x, y and z data


plot(x,y,z)

• Display of a digital image (each element of the matrix c specifies the colour of an
individual pixel)
image(c)

Introduction to MATLAB Derek Lichti


18

8 A WORKED EXAMPLE

8.1 Problem Statement


Estimation of the coefficients of a polynomial that optimally fits a set of point
observations is a classic problem for which the least-squares method is utilised. As an
example, consider the set of point observations (x and y co-ordinates) listed in Table
8.1.

Table 8.1. Observed Point Co-ordinates.


i xi yi
1 0 4.26
2 1.5 4.58
3 2 4.33
4 4 1.45
5 5.2 -1.61

Required is a parabola that best fits these data points. Given that a parabola can be
parameterised as

yi = a 0 + a1x i + a 2 x 2i , (8.1)

the problem boils down to determination of the coefficients a0, a1 and a2. Since there
are 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 the
observations.

8.2 Least-Squares Solution


The least-squares solution begins with formation of a system of observation equations
having 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 misclosure
vector, in this case, is comprised of the observed y co-ordinates, and the elements of
the residual vector represent the deviations of the data points from the best-fit
parabola. The parameter and residual vectors are estimable quantities.

The formation and solution of Equation 8.2 is the core subject of Measurement and
Adjustment Analysis. Neglecting for the moment the processes behind its formation,
the form of this equation is given by

Introduction to MATLAB Derek Lichti


19

é1 x1 x12 ù é − y1 ù é r1 ù
ê 2ú ê ú ê ú
ê1 x2 x 2 ú éa 0 ù ê− y2 ú ê r2 ú
ê1 ê ú
x3 x 32 ú ê a1 ú + ê − y3 ú = ê r3 ú
ê ú ê ú ê ú
ê1 x4 x 42 ú êëa 2 úû ê− y4 ú ê r4 ú
ê1 x 52 úû êë − y5 úû êë r5 úû
ë x5
(8.3)
é1 0 0 ù é−4.26ù é r1 ù
ê1 15. 2.25 éa 0 ù ê −4.58ú ê r2 ú
ú
ê ú ê ú ê ú
ê1 2 4 ú ê a1 ú + ê−4.22ú = ê r3 ú
ê úê ú ê ú ê ú
ê 1 4 16 ú êëa 2 úû ê −145
. ú ê r4 ú
êë1 5.2 27.04úû . úû êë r5 úû
êë 161

The least-squares solution is given (without proof) by

( )
−1
x = − A TA A Tw . (8.4)

Some other quantities of interest are the residual vector, r, computed via Equation 8.2,
and the estimated variance factor, σ 20 , given by

rTr
σ 20 = (8.5)
n−u

where n is the number of observations (5) and u the number of unknowns (3).

8.3 Solution in MATLAB


The MATLAB solution to the parabola fit problem has been formulated in a modular
fashion. That is, each major task, such as file input, least-squares solution, etc., is
located in a separate function M-file that is called by a main script M-file. The
organisation is depicted in Table 8.2.

Table 8.2. MATLAB M-File Organisation.


M-File Role
example.m main script file
my_input.m file input of point data
form_eq.m form observation equations
solution.m least squares solution
my_output.m formatted output of results
my_plot.m plotting of results

The source code for each file is given in Appendix A. The comments explain the
function of each block of code. Note the documentation at the top of each M-file to
indicate the purpose, arguments, return values, author and creation date. Read through
the code carefully to become familiar with the style and good programming practise.

Introduction to MATLAB Derek Lichti


20

The input data (the last two columns of Table 8.1) were contained within a text file
called data.txt, the contents of which are shown below.

0 4.26
1.5 4.58
2 4.33
4 1.45
5.2 -1.61

8.4 Results
The formatted output, written to file data.out, is given below.

A matrix
1.0000 0.0000 0.0000
1.0000 1.5000 2.2500
1.0000 2.0000 4.0000
1.0000 4.0000 16.0000
1.0000 5.2000 27.0400

w vector
-4.2600
-4.5800
-4.3300
-1.4500
1.6100

solution vector
4.2662
0.7486
-0.3617

residual vector
0.0062
-0.0047
-0.0134
0.0234
-0.0115

variance factor 0.0005

The MATLAB plot of the data points and best-fit parabola is shown in Figure 8.1.

Introduction to MATLAB Derek Lichti


21

-1

-2

-3

-4

-5
-1 0 1 2 3 4 5 6

Figure 8.1. Observed Data Points and Best-Fit Parabola.

Introduction to MATLAB Derek Lichti


22

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)
break
end

% form observation equations


[A,w]=form_eq(x,y);

% least squares solution


[sol_vect,resid,vf]=ls_solution(A,w);

% file output of results


my_output(A,w,sol_vect,resid,vf,'data.out');

% plotting of results
my_plot(x,y,sol_vect);

% ***end of file***

Introduction to MATLAB Derek Lichti


23

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 mode


fid=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 numbers
temp= fscanf(fid,'%f',[2,inf]);

% transpose and divide temporary matrix into x and y


temp=temp';

% this assigns all elements the first column to x


x=temp(:,1);
% this assigns all elements the second column to y
y=temp(:,2);

% close file--very important


fclose(fid);

% ***end of file***

Introduction to MATLAB Derek Lichti


24

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 points


n=max(size(x));

% allocate memory
A=zeros(n,3);
w=zeros(n,1);

% form A and w
for 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***

Introduction to MATLAB Derek Lichti


25

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 vector


sol_vect=-inv(A'*A)*A'*w;

% residual vector
resid=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***

Introduction to MATLAB Derek Lichti


26

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 mode


fid=fopen(filename,'wt');

% check fid for success of file open request


% note use of logical equal operator ==
if (fid == -1)
return
end

% determine n and u from A


[n,u]=size(A);

% write output with specified precision

% A matrix--note use of field width and precision values


fprintf(fid,'A matrix\n');
for i=1:n
for j=1:u
fprintf(fid,'%8.4f',A(i,j));
end
fprintf(fid,'\n');
end

% other quantities
fprintf(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 file
fclose(fid);

% ***end of file***

Introduction to MATLAB Derek Lichti


27

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 graph


hold on

% plot curve from -1 to 6 with 100 linearly spaced values


x_curve=linspace(-1,6);

% calc curve from solution vector


n=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***

Introduction to MATLAB Derek Lichti

Вам также может понравиться