LAB 4 MATLAB

advertisement
COMPUTER APPLICATIONS IN THE GEOSCIENCES
LAB 4  MATLAB
MATLAB INTRODUCTION
Matlab is a commercial product that is used widely by students and faculty and
researchers at UTEP. It provides a "high-level" programming environment for
computing with a special emphasis on matrix operations.
Many specialized
functions are "hard wired" into Matlab so there is no need to use subroutine
libraries for these tasks. It is also very easy to make plots of Matlab output-many plotting functions like are also built into the program.
Matlab is available for PCs, Macs, and UNIX workstations. The student version
of Matlab currently sells for about $100 at the UTEP bookstore. We have a site
license for Matlab on the department network, however this is limited to
university computers only. You may also obtain a copy of Matlab from UTEP’s
My Desktop service (see directions posted on class website).
Matlab is more user-friendly and easier to learn than standard languages like
Fortran and C. It is good for many problems, but ultimately does not have the
flexibility of C or Fortran. Complicated Matlab scripts will often run much slower
than the Fortran or C equivalent.
Matlab is well documented with online help (look to the menu bar when you are
running the program). There are also many books written about Matlab that
you may find useful if you become a serious user. The following is a brief
introduction to help you get started and to demonstrate some of Matlab’s
capabilities.
Matlab can be used interactively as a
powerfully, run using scripts (i.e., programs).
 PCs:
super
hand
calculator,
or,
more
A Matlab icon can be found on your desktop.
 Macs: Go to Macintosh HD  Applications  Matlab  and drag
the Matlab icon to your doc (for future use).
Start Matlab and several blank screens, including a Command Window, should
appear……….
Notes compiled by B. Konter (UTEP) and P. Shearer (UCSD)
COMPUTER APPLICATIONS IN THE GEOSCIENCES
Command window
#1.
Prompt and easy addition
>>
At the >> prompt, one can directly enter commands.
As an example, the
following is one way to compute 2+2: (Try it, you enter the bold, black info
and Matlab returns the gray info)
>> a = 2
a =
2
>> b = 2
2
COMPUTER APPLICATIONS IN THE GEOSCIENCES
b =
2
>> c = a + b
c =
4
#2.
The semi-colon (;)
It is often annoying to have Matlab always print out the value of each variable.
To avoid this, put a semicolon(;) after the commands:
>>
>>
>>
>>
a = 2;
b = 2;
c = a + b;
c
c =
4
Only the final line produces output. Semicolons can also be used to string
together more than one command on the same line:
>> a = 2; b = 2; c = a + b; c
c =
4
#3.
More complicated math
Now try an example for computing a quadratic equation, which includes
multiplication (*), division (/), square-root (sqrt), and powers (^). Also note that
parentheses are used to determine the order of operations.
>> a = 2;
>> b = -12;
3
COMPUTER APPLICATIONS IN THE GEOSCIENCES
>> c = 16;
>> quad1 = (-b + sqrt(b^2 - 4*a*c)) / (2*a)
quad1 =
4
#4.
More complicated math:
Trig functions
Trig functions are also supported by Matlab.
functions must be in radians, not degrees:
Note that the arguments of trig
>> y = sin (pi/6)
y =
0.5000
Note that "pi" is hardwired to the value of pi (3.14..); you don't have to set this.
#5.
Whos (what are my variables?)
To see all the variables currently defined in Matlab’s current session (that you
entered), use the "whos" command:
>> whos
Name
Size
a
b
c
quad1
y
1x1
1x1
1x1
1x1
1x1
Bytes
8
8
8
8
8
Class
double
double
double
double
double
array
array
array
array
array
To remove all variables from memory, use the "clear" command:
>> clear
>> whos
4
COMPUTER APPLICATIONS IN THE GEOSCIENCES
>>
# 6. Using a Matlab script (*.m) file
A script is a text file containing lines of Matlab commands (e.g. testscript.m). To
run a script, simply type the name of your script, but without the “.m” suffix, at
the Matlab prompt (example below, but it won’t work until you have the file):
>> testscript
By doing this, Matlab simply executes each line one at a time, exactly as if you
had typed each line into the command window. In your script, you can create
lines beginning with a “%” sign, which are understood by Matlab to be
comments about the code (and are ignored). Example:
% At the first line of my code, I should always put my name
% At the second line of my code, I should enter a
% description of what the program is going to do.
A script can be written with the built-in Matlab Editor, or you can open up an
existing script that someone gave you.
Here you will do both.
First, make a new Lab4 folder in your \\geobase\geo4315 directory and
copy/paste to your Lab4 folder (yes, please copy) the following file from the
Instructor folder on \\geobase:
Instructor/Matlab_stuff/testscript.m
To run a script, you need to tell Matlab where to look for the *.m files that you
want to run. To do this, you’ll want to set the “Current Directory” to your
working folder, so for this exercise it will be your Lab5 folder on \\geobase. In
the top Matlab window, look for the icon “…” (see below) and click on it to
navigate to your Lab4 folder.
GEO4315/yourdirectory/Lab4
Next you will need to open up the Matlab Editor window:
5
COMPUTER APPLICATIONS IN THE GEOSCIENCES
Desktop  Editor.
A new, separate window should appear.
Now open the testscript.m file:
File  Open  select testscript.m
Familiarize yourself with the content of the script (read through it). Try to
interpret what the code is doing and what will appear when you execute the
code.
This step is really important, as you will be creating your own script in
the next exercise.
Nex run the program in the Matlab window by typing:
>> testscript
 What did this program do?
 Draw a sketch of the resulting figure of testscript.m program below:
6
COMPUTER APPLICATIONS IN THE GEOSCIENCES
# 7. Creating a new Matlab script (*.m) file
Next you will create a new Matlab script to plot an example set of x-y data
points. The file with these example points is called test_data.dat and is located
in the \\geobase\geo4315\Instructor\Matlab_stuff folder.
Copy this file to
your own Lab4 folder.
If you have problems getting this file from the Instructor
folder, you can also go to the class website and download the file there (Click
on the Matlab link from the schedule).
Open up test_data.dat file in the Matlab Editor to inspect its contents: File 
Open  test_data.dat
The first column of the data will be the ‘x’ column (pretend it is earthquake
depths), and the second column of data will be the ‘y’ column (pretend it
represents earthquake magnitudes). You will use these values to create an x-y
plot.
Contents of test_data.dat:
10.0
15.0
5.0
20.0
22.0
4.0
30.0
10.0
12.0
6.0
14.0
3.0
3.3
1.3
5.9
6.7
1.1
5.8
3.9
7.2
3.3
2.2
You will now build a script (a .m file) that will open, read, and plot this fictitious
dataset.
7
COMPUTER APPLICATIONS IN THE GEOSCIENCES
First open a new Matlab file in the Editor window:
File  New  M-File
Type the following commands in the Matlab file (yes, all of them):
% Matlab script to practice loading a simple data file
% and creating an x-y plot.
% first load the sample data file, named test_data.dat
load test_data.dat
% assign the first column of this file to be “x” values
% The following syntax says grab “all rows” (:)
% of the “first column” (1) of the file test_data
x = test_data(:,1);
% next assign the second column of the file to be “y”
% values
y = test_data(:,2);
% now check to make sure the data was loaded properly
whos
% now plot x vs. y and label each data point with a red *
% symbol. I can type “help plot” for other symbols and
% colors to use
figure(1)
% opens up the first figure window
plot (x ,y , ’r*’ )
% plot x vs. y
grid
% this enters a grid in the figure
xlabel(‘earthquake depths (km)’)
% label the x-axis
ylabel(‘earthquake magnitudes’)
% label the y-axis
title(‘Earthquakes in the xxx’)
% add a title
Save your Matlab file with the name ‘myscript.m’:
File  SaveAS
Now copy each line, line by line, that does not begin with a “%” sign, into the
Matlab window.
Observe what each line does.
Next clear Matlab (type:
clear) and close the Figure window.
Now run the entire script at once by typing the name of your script (without the
“.m”) into the Matlab window and hit return.
8
COMPUTER APPLICATIONS IN THE GEOSCIENCES
Congratulations, you have just created and executed a Matlab script!!!!!
To save your Figure to a file, click on the following in the Figure window:
 SaveAs  name it myscriptfigure and select .pdf option for File
Format
File
# 7. Performing math operations on a column of data
Now you will practice a few math operations, just like you did in Excel, by
treating each of your data values as a “column” that you will operate on.
In
the previous step, you stored all of the first column of data as “x” and the
second column as “y”.
Below are the steps for calculating the average of
each and then normalizing (dividing) your data by the average. Matlab has a
built-in function for computing the average (or mean) of a data set.
First calculate the average of the x-values (you can hand-type these in or
append them to your Matlab script above):
>> avg_x = mean(x)
Matlab returns
___________________ (enter it here)
Now calculate the average of the y-values:
>> avg_y = mean(y)
Matlab returns
___________________ (enter it here)
Divide x by avg_x and call this a new variable.
>> norm_x = x/avg_x
Do the same for the y values:
>> norm_y = y/avg_y
Now print your new and old values to the screen:
>> [x
y
norm_x
norm_y]
9
COMPUTER APPLICATIONS IN THE GEOSCIENCES
To save these values to a file, assign all of them one name (new_vals), and
print the 4 columns to a file. Below are the commands to use. You will need
to transpose your data columns (using the ‘ command) to ensure that the
fprintf command below writes the data in the correct order.
>> new_vals = [x y norm_x norm_y]’;
% transpose here
>> fid = fopen(‘mytest_data.dat’,’w+’);
>> fprintf(fid,’%6.2f %6.2f %6.2f %6.2f\n’, new_vals);
>> fclose(fid);
Note that in the above “fprintf” statement, you first give Matlab the command to
open up a new, empty file. You specify the name of the new file with the first
entry (‘mytest_data.dat’). You also tell Matlab that you want to write to the new
file with the ‘w+’ entry.
Then you issue the print-to-this-file statement with the ‘fprintf’ command.
The
‘fid’ entry just reminds Matlab where it stored the name of the new file in
memory. A series of ‘%6.2f’ are entered, which represents the format of each
column that you are saving to the file (along with how many decimals to round
to). If you were going to save 5 columns to a file, you’d include 5 “%6.2f”
entries, with the last one followed by a “\n” as in the example above (this
means start a new line after the last column). Last, you enter the name of the
variable in Matlab that you want to print to the file.
In this case, you assigned
the name “new_vals” for the variable holding the 4 columns of data. For more
information on the fprintf command, type “help fprintf”.
Finally, you close the file that you first opened with the ‘fclose’ command.
!! Note !!
Many students get errors or strange results when trying to
issue these print-to-file commands above.
To check your work, open up
the new file you created (mytest_data.dat) and check that it makes sense.
Are all of your expected “x” values in the 1st column, “y” values in the
2nd column, etc.? If not, then you had a typo in your commands.
10
COMPUTER APPLICATIONS IN THE GEOSCIENCES
# 8. Now you’re on your own….
Following the steps above, you will now use a real data file (the earthquakes
you retrieved from the USGS website for the Excel Lab) to:
- load into Matlab
- plot the data
- calculate the normalized depths and magnitudes
- print the new values to a new file
First copy the file called USGS_earthquakes.dat from the
\\geobase\geo4315\Instructor\Matlab_stuff folder, to your Lab4 folder.
this file can also be found on the class website if you need it.
Again,
Open this file up in Matlab’s Editor window and review the contents.
columns are arranged in the following order:
Date (YYYYMMDD)
Latitude
Longitude
Depths (km)
The
Magnitudes
Step 0.
Write a Matlab script (name it [a good name, you pick].m) that
contains the commands for performing the following steps. Follow the steps
below to construct this script. Make sure you check your script by running it in
Matlab. Also make sure to provide thorough comments in the script (denoted
with a % symbol) that tell me what you are doing at each step.
Step 1.
Load the USGS_earthquakes.dat file in Matlab and assign variable
names to each column of data.
Hint:
>> date = USGS_earthquakes(:,1);
Step 2. Plot the Magnitudes vs. Depths of you data. Magnitudes should be
along the horizontal axis, and Depths along the vertical.
Plot each data point
as a magenta (‘m’) diamond. Give your plot x- and y-labels, a title, and a grid.
Save this plot as a .pdf file.
Step 3. Calculate the average of both your magnitudes data and your depth
data. Then use these values to calculate normalized magnitudes and depths,
exactly as you did in Excel and in the previous example.
Step 4. Assign a variable to store all of your original data, plus the two new
columns of data (normalized values) you calculated.
11
COMPUTER APPLICATIONS IN THE GEOSCIENCES
Hint:
>> new_dat = [date latitude longitude mag depth norm_mag norm_depth]’ ;
Step 5.
Print the above (‘new_dat’) variable to a file.
commands as given in the previous example.
Use the fprintf
Step 6. Copy the following to the DROPBOX folder, contained inside a folder
labeled with your name and Lab4.
-
myscriptfigure.pdf (the figure resulting from running myscript.m)
mytest_data.dat (the new test data file you printed with the normalized values)
Earthquake Figure (the figure resulting from above, Section 8 Step 2)
New Earthquake file (the new file resulting from above, Section 8 Step 5).
Extra Credit (1): What significant event is captured with this data?
you know? (required for M.S. and Ph.D. students)
How do
Extra Credit (2): Try using the histogram function of Matlab. Look up the
histogram function (hist) with the help command, and then use it to plot a
histogram of your original earthquake depths and your original earthquake
magnitudes (2 separate histograms). You can choose to bin the data however
you like (but it should make some sense). For full credit, label your axes (with
UNITS!!!), give your plots sensible titles, print them to pdf files, and post on your
website.
(required for M.S. and Ph.D. students)
12
Download