GS550

Spatial Data Analysis II

Spring 2004

Individual assignment No. 1

Due Wednesday, April 9, 2004

The following pages contain a set of exercises designed for you to help you get familiar with MATLAB environment and programming language.

1.  Follow all the examples closely and make sure that you understand all commands specified there. The examples are grouped according to sub-topics, which are of a primary importance, while learning MATLAB .

  1. Once you completed all the examples above, continue to the section Your assignment and follow the instructions given there.
  1. Remember, you can always use the on-line help, by typing help in the MATLAB prompt area. This will bring a help menu, so choose the topic that you need to study more.
  1. Have fun!

Basic Matrix and Vector Operations

1.  Load matrix A= [1 2 3; 4 0 2; 6 7 2] into a workspace.

2.  Load matrix B= A+2 into a workspace

3.  Check the content of your workspace by typing who

Note: command whos will list all the variables, their types and sizes

Note: MATLAB is case-sensitive, so ‘a’ and ‘A’ are two different variables

4.  Check the size of A matrix by typing size(A)

5.  Find matrix AT, which is a transpose of A: AT=A’

6.  Find matrix S=A+B

7.  Find matrix D=A-B

8.  Find matrix P=A*B

9.  Find inverse I of A*B: I=inv(P)

10.  Check your inverse by typing: I*P

11.  Define vectors a =[1 2 3] and b=[2 3 4]

Note: You can create vectors a and by also by typing: a=1:3, b=2:4

12.  Find the length of vector a by typing length(a)

13.  Find aA=a*A

14.  Find sum of all diagonal elements of matrix A: sum=A(1,1)+A(2,2)+A(3,3)

15.  You can do the same thing by using “for” loop, especially if A matrix is rather large:

[n,m]=size(A);

sum=0;

for i=1:n

for j=1:m

if(i==j)

sum=sum+A(i,j);

break

end

end

end

‘check sum’

sum

16.  Create a matix, Aext, by extending your 3 by 3 matrix A by one column of zeros by typing:

Aext=A;

Aext(3,4)=0

17.  Place 1 in the new column of Aext: Aext(1:3, 4) =1

Note: 1:3 stands for “rows 1 to 3”, and 4 denotes the 4th column of matrix Aext

Matrices “Ready to Use”

1.  Create 2 by 2 matrix of zeros: Zero=zeros(2,2)

2.  Now type Zero1=zeros(3,3); (note that semicolon is a part of the command now). This time MATLAB will not print the Zero1 matrix for you, even if it created it; the semicolon at the end of the command means “do not print the result to the screen” or “suppress the output”

3.  If you now type Zero1 you will see that the matrix is there!

4.  Create 2 by 2 matrix of ones by typing One= ones(2,2)

5.  Create 2 by 2 identity matrix by typing I=eye(2,2)

6.  Create a 2 by 2 diagonal matrix with 2 on the main diagonal: V=I*2 (useful in creating a diagonal covariance matrix for observations with the same variance)

7.  If the diagonal elements are not equal, you can create your covariance matrix as follows:

a.  Define vector containing the variances v = [1 2 1]

b.  Get the matrix V = diag(v)

8.  Find matrix product ATV-1A by typing A’*inv(V)*A

9.  Create matrix BIG1 by concatenation of matrices A and B vertically; BIG1= [A; B]

10.  Create matrix BIG2 by concatenation of matrices A and B horizontally; BIG2= [A B]

11.  Create matrix BIG3 by concatenation of matrices A and B horizontally and vertically and adding 1 to one of the matrices A in the new matrix BIG3; BIG3= [A+1 B; B A]

12.  Now create a matrix BIG4 which is identical to BIG3 but has the second column deleted

BIG4 = BIG3

BIG4(:,2) = []

Note: “:” as a first subscript of BIG4 means “all rows” in column 2

Saving, Viewing and Loading Your Workspace

1.  Save your workspace under the name GS550 by typing: save GS550

2.  Type dir or what to check if you got it; you should see “GS550.mat” in your directory listing

3.  Type clear to delete all the variables from your workspace; then type who to see if you actually deleted all of them

4.  Then you can get all your variables back by loading the workspace GS550 that you saved before; type load GS550 to get it; “load workspace” is also available from the File menu

5.  Type who to check if you have all your variables back

.m File

Instead of typing all the commands in the MATLAB prompt line one by one, you can prepare a text file, called xxx.m (where xxx is any name you chose), which contains all the commands and data specification, and execute the file by typing its name “xxx” in the MATLAB prompt line.

Example: file test.mat

% load data

A= [1 2 3; 4 0 2; 6 7 2]

%check the size of the matrix

[n,m]=size(A);

sum=0;

%compute the sum of diagonal elements of A

for i=1:n

for j=1:m

if(i==j)

sum=sum+A(i,j);

break

end

end

end

'check sum'

sum

Note: % denotes the comment line

Note: Location of your file test.m should be placed on MATLAB path, otherwise you need to specify the directory where the file is located, or better yet, place the file in your working directory. Directory change is done in MATLAB by typing, for example: cd c:\test\mytest. To set your working directory (\home\goodstuff) on MATLAB ’s path, do the following:

1.  Type path in MATLAB prompt line to see the current path

2.  Set the new path to be added to the existing one:

In Unix: path(path,’/home/goodstuff’)

In DOS: path(path, ‘home\goodstuff’)

Long Command Lines

For long command lines use three periods, …, followed by Return to indicate that the statement is continued in the next line. For example:

Estimate = 1 + 2+ 3- 23 +11 +45 – 3 –56/3 – 4 … (press Return key)

+2/4 – 5/6 +45 (continue typing)

Data Import/Export

Data can be typed in the prompt line, if you have a small amount of data. For bigger amounts of data, you can create either ASCII (text) or binary file and import it to your workspace using MATLAB commands as shown below in the example. The same applies to the data files created by other applications.

1.  Create a small text data file (you can use Notepad to get xxx.txt file or use MATLAB File menu to create a xxx.m file)

For example, create file data.m containing the following data:

1 123.23 234.34 345.34

2 124.23 235.55 346.33

3 122.33 234.45 344.44

Where the first column is the point ID, 2nd, 3rd and 4th are X, Y, Z coordinates

2.  Load the data to MATLAB workspace by typing: load data.m

3.  Check what you got: type who

4.  ‘data’ should be listed as a variable now

5.  Lets plot the X and Y coordinates of all three points and mark them with *:

plot(data(:,2), data(:,3),’*’)

xlabel(‘ X coordinate in meters ‘)

ylabel(‘ Y coordinate in meters ‘)

title(‘ Horizontal coordinates ‘)

legend(‘point’)

grid (optional!)

6.  Now add two more points to your data file

data(4,1) = 4, data(4,2) = 124.55, data(4,3) = 236.75, data(4,4) = 247.22

data(5,1) = 5, data(5,2) = 125.10, data(5,3) = 233.75, data(5,4) = 243.22

7.  Hold the plot to add new points by typing hold

8.  Type the new points in green using + sign

plot(data(4:5,2), data(4:5,3),’ +g’)

9.  Correct the legend by typing legend(‘old points’, ‘new points’)

10.  Write data to the new file called data.out

a.  Open the file: [fid,message]=fopen(‘data.out’,’wt’) where fid is a scalar integer assigned to –1 if file cannot be open, or is positive if the file was open; ‘wt’ stands for “open the text file for writing”; message will give the error message if the open is not successful.

b.  Write ‘data’ to the file according to the specified format, and close the file:

for i=1:5

fprintf(fid,‘%d %12.3f %12.3f %12.3f\n’, data(i,1), data(i,2), data(i,3),data(i,4))

end

fclose(fid)

You should now have a new file ‘data.out’ with the following content:

1 123.230 234.340 345.340

2 124.230 235.550 346.330

3 122.330 234.450 344.440

4 124.550 236.750 247.220

5 125.100 233.750 243.220

11.  Create a binary file data.bin containing the same information as data.out

a.  Get the data from data.out: load data.out (optional, since data should be now a part of your workspace)

b.  Open a new binary file data.bin for writing: [fid,message]=fopen(‘data.bin’,’wb’)

c.  Write data to the new file

count = fwrite(fid, data(:,1), ‘integer*4’) (write the first column)

count = fwrite(fid, data(:,2:4), ‘double’) (write columns 2, 3 and 4)

fclose(fid)

fwrite writes the elements of matrix ‘data’ to the file fid, translating MATLAB values to the specified precision (first we write the column of IDs, then the three columns of coordinates). The data are written in column order; count is the number of elements successfully written, which you can see on the screen.

12.  Now read the data from the binary file data.bin

a.  [fid,message]=fopen(‘data.bin’,’rb’)

b.  fseek(fid,0,-1); (this is optional, but makes sure that we are at the beginning of the file)

c.  [new_data, count] = fread(fid, [5,1], ‘integer*4’) (read the first column of data to new_data)

d.  [new_data(:,2:4), count] = fread(fid, [5,4], ‘double’) (read columns 2, 3 and 4 of data into new_data)

e.  fclose(fid) (close data.bin)

f.  Now new_data is a new variable in your workspace, but if you want to have it next time you work with GS550, save GS550 again, and it will add all new variables that you created.

Your assignment:

Given:

X = 123.230 (m)

Y = 234.340 (m)

Z = 345.340 (m)

1.  Create an ASCII file ‘my_data.m’ (in MATLAB editor) containing a 5:4 matrix

0.683806176767331 0.717612967126723 0.132063401540227 27.6240579113364

0.744185013441521 0.661424485205242 0.093307642451854 -49.7443703301251

-0.734269091440814 0.633619131062194 -0.243671291100146 31.7140723355114

0.651730143911132 -0.333641240021721 -0.681125056413499 25.6096501983702

0.257950248091081 0.763840928806754 -0.591615335322996 1.0817370973527

which would represent your coefficient matrix A from the least squares problem (first three columns) and the observation vector Y (the last column). Save the file.

2.  Load the data from the my_data.m file

3.  Create a matrix A and a vector Y from these data

4.  Create a diagonal covariance matrix V with ‘0.02’ on the main diagonal

5.  Compute ATV-1A and ATV-1Y

6.  Find the unknown vector x= ( ATV-1A) -1 ATV-1Y (note: the unknown x-vector is the corrections to your coordinates X, Y, Z (given above))

7.  Based on these corrections, compute new values for X, Y and Z coordinates.

e.g.

8.  Open a new ASCII file ‘coords.m’ and write the new coordinates (corrected) X, Y, Z to this file.

9.  Make a 3-D Plot (i.e. use plot3 function) for the new coordinates (resulting in a single point graph!), properly label and title your plot (X, Y and Z axis)

10.  Make a print out showing all you operations and the data that you used (investigate the DIARY option in MATLAD for getting it done: in MATLAB prompt type help diary to get more info about this option; or simply cut and paste from the MATLAB window to a text file.

10. Print the plot that you created.

TOPICS COVERED

1.  Basic Matrix and Vector Operations

·  defining a matrix

·  sum, product, transpose, etc.

·  length of a vector and matrix size

·  sum of diagonal elements (by summing all elements and by using for loop)

·  expanding a matrix

2.  Matrices “Ready to Use”

·  matrix of ones (ones(2,2))

·  matrix of zeros (zeros(2,2))

·  diagonal matrix (eye(2,2) * number)

·  matrix concatenation

·  subscript notation “:” means all columns or all rows; A(:,1) denotes first column of A

3.  Saving, Viewing and Loading Your Workspace

·  dir and what commands

·  save and clear commands

·  who and whos commands

·  load commands

4.  xxx.m File

·  file created by MATLAB editor

·  stores the actual code or the data

·  MATLAB path definition

·  adding new directories to the path

5.  Long Command Lines

·  Use … to indicate line continuation

6.  Data Import/Export

·  ASCII and binary files

·  file opening and closing (fopen, fclose functions)

[FID, MESSAGE] = FOPEN(FILENAME,PERMISSION)

FCLOSE(FID)

·  loading data from ASCII file (load filename)

·  reading a binary file (fread function)

[A, COUNT] = FREAD(FID,SIZE,PRECISION) reads binary data from the

specified file and writes it into matrix A. Optional output argument COUNT returns the number of elements successfully read. The size argument is optional; if not specified, the entire file is read

·  writing to ASCII file (fprintf function)

COUNT = FPRINTF(FID,FORMAT,A,...) formats the data in the real part of matrix A, under control of the specified FORMAT string, and writes it to the file

associated with file identifier FID. COUNT is the number of bytes successfully written.

FORMAT is a string containing C language conversion specifications. Conversion specifications involve the character %, optional flags, optional width and precision fields, optional subtype specifier, and conversion characters d, i, o, u, x, X, f, e, E, g, G, c, and s. See the Language Reference Guide or a C manual for complete details.

The special formats \n,\r,\t,\b,\f can be used to produce linefeed, carriage return, tab, backspace, and formfeed characters respectively. Use \\ to produce a backslash character and %% to produce the percent character.

x = 0:.1:1; y = [x; exp(x)];

fid = fopen('exp.txt','w');

fprintf(fid,'%6.2f %12.8f\n',y);

fclose(fid);

·  writing to binary file (fwrite function)

COUNT = FWRITE(FID,A, PRECISION) writes the elements of matrix A to the specified file, translating MATLAB values to the specified precision. The data are written in column order. COUNT is the number of elements successfully written.

fid = fopen('magic5.bin','wb')

fwrite(fid, magic(5),'integer*4')

creates a 100-byte binary file, containing the 25 elements of the 5-by-5 magic square, stored as 4-byte integers.

·  plot function (see help plot to check all the options for plotting)

Example of reading a binary file: