Professional Documents
Culture Documents
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
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.
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
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.
Once initialisation has completed, a window structure similar to that shown in Figure
2.1 should be visible.
Workspace
Command Window
Command History
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
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.
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.
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!
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.
load filename
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 --
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
help inv
Help can also be accessed with the Help button on the tool bar, as shown in Figure
2.2.
exit
3 VARIABLES
• Row vector:
r = [ 1 2 3 4]
• Matrix (method 2)
mat_m2 = [ 1 2 3
4 5 6
7 8 9 ]
• 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.
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
x=[ 1 ; 2 ; 3];
whos
Name Size Bytes Class
x 3x1 24 double array
Grand total is 3 elements using 24 bytes
help format
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).
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.
a=[1 2; 3 4]
a =
1 2
3 4
a*a
ans =
7 10
15 22
a.*a
ans =
1 4
9 16
help matfun
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
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.
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.
into the MATLAB environment. Examples of some of the most pertinent constructs
are given below.
n=10;
x=zeros(n);
for j=1:n
x(j)=j*10;
end
c=0;
while c >= 10
c=c+1;
end
if x == 10
y=5;
else if x > 10
y=4;
else
y=3;
end
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.
help lang
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,
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.
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
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
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.
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.
• Display of a digital image (each element of the matrix c specifies the colour of an
individual pixel)
image(c)
8 A WORKED EXAMPLE
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.
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
é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
( )
−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).
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.
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
The MATLAB plot of the data points and best-fit parabola is shown in Figure 8.1.
-1
-2
-3
-4
-5
-1 0 1 2 3 4 5 6
% example.m
% purpose: main script file for the least squares solution
% of the best fit parabola example
% Derek Lichti
% 28 August 2001
% check for file open error and for minmum number of observations (3)
if (size(x) < 1)
break
end
% plotting of results
my_plot(x,y,sol_vect);
% ***end of file***
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
% ***end of file***
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
% 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***
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
% residual vector
resid=A*sol_vect+w;
var_fact=resid'*resid/(n-u);
% ***end of file***
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
% 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
% close file
fclose(fid);
% ***end of file***
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
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***