Lab 1

advertisement
Name __________________________
Oceanographic & Meteorological Quantitative Methods – SO335 Lab 1 – (100 pts)
MATLAB Background
The objectives of Lab 1 are to familiarize SO335 students with MATLAB. There are two
basic interfaces to MATLAB: the command window and the script. We will spend the
majority of this semester writing and executing code in scripts, and in this lab, we will
introduce you to both the command window and scripts.
MATLAB interface
1. Open up your copy of MATLAB. You should notice four windows as seen in Figure 1:
Fig. 1 –MATLAB program interface showing the Command window (Large center window),
the Command History window (lower left window), the current directory window (upper left
window), and the Workspace window (right panel).
1. The Command window, usually a large window located in the center of the screen, is
used for typing in variables, functions and commands or scripts (Otherwise known as m-files).
b. The Command History window, located in the lower left, logs statements entered in the
command window.
c. The Workspace window located in the right – you will see a list of any created variables
from your current project along with their size and format.
d. The Current Folder window, located in the upper left, shows any files that you have saved
in the current folder (C:\users\bbarrett\Documents\MATLAB for me).
2. When we start to create files in MATLAB, it will be important to know where those files
are located.
1
Change your working directory to the following:
C:\users\mXXXXXX\Documents\MATLAB\ (You can choose another related folder
if you wish. Whichever folder you choose, remember that you must tell
MATLAB to “look there” (by changing the Current Folder) for any saved files,
etc. I.e., typing load file.mat will not work if file.mat is saved in another folder.)
To change the directory, select the ellipses button (. . .) to the right of the current directory
address bar. You can now browse for the selected folder.
3. Notice the menus available in the toolbar on the topic. Many of them are common to other
windows-based applications:
a. Click on the help menu using the following tree:
Help -> MATLAB Help (F1)
b. Notice that MATLAB Help can be accessed quickly using the F1 key.
MATLAB Basics – The following sections is to give you some familiarity with the basic
features of MATLAB. The exercises are rudimentary in nature but the concepts within each
section require time and thought in order to become comfortable with MATLAB. Do not
rush through this lab. Save all of your script files and lab papers. Concepts we cover here
will return in later weeks!
(15 pts) MATLAB command window – Performing basic arithmetic. Although the true
utility of MATLAB is far beyond just a simple calculator, we will start with simple
calculations. In these Labs, MATLAB commands will typically be presented in bold. For
each of these operations, (a) write a short sentence describing what MATLAB is calculating,
and (b) write the value that is returned to you when entering these at the command window
prompt. For help in understanding what the commands are doing, you can always type help
<command>, and then press enter, where you replace <command> with sin, sind, exp,
sqrt, quiver, contour, clabel, meshgrid, etc.
a. sin(pi/2)
b. sind(45)
c. exp(pi)
d. 2.^5
e. (1+sqrt(5))./2
f. log(exp(1))
2
g. (3+5).*(4+6) **Notice here that you can’t just type (3+5)(4+6). MATLAB
needs to know the operation between the two parenthetical groups.
Notice that after every command, MATLAB displays an associated output. To prevent
MATLAB from displaying anything, add a semi-colon (;) at the end of the command. This
will be helpful if one is manipulating large dimensional arrays that occupy a lot of space. For
example, instead of typing
log(exp(1))
Suppress the output by typing
log(exp(1));
MATLAB SCRIPTS
The majority of the semester, we will be working in script files. In MATLAB, script files are
saved with extension “.m”. To execute all of the lines of a script, you can press the green
“Run” arrow. To execute individual lines of a script, highlight them with the mouse and then
either right-click and select “Evaluate Selection”, or press F9 on the keyboard. In all cases,
when you run a script (or part of a script), some output may be displayed back in the
command window. Always check the command window after executing a script (or part of a
script). Error messages will appear there (in red). If the command prompt >> appears again
after executing a script, it ran without any errors.
(10 pts) Let’s create a script with all of the seven math expressions (a-g above) that you typed
into the command prompt. Open a new script file, and on the very first line, type the
following
% SO335 Lab 1. 13 Aug 2014. MIDN XXXX XXXX (replace the date with
today’s date, and XXXX XXXX with your First and Last Name).
The “%” symbol is a flag that denotes comments. A great coding practice is to comment
everything, liberally. Not only do the comments remind you of what you are doing
(especially important if a few days lapse between when you work on your code), but
comments also personalize your code for you. Comments can be on their own line, or placed
to the right of code that is executed by MATLAB.
A few lines below the header comment, type each of the above expressions on a new line.
Comment each expression **on the same line as the expression**. Save the script file as
“Lab1_xxxxx.m”, where “xxxxx” is your Last Name, and then execute it. What happened
(look in the Command Window). If there are errors, correct them. If you have output
displayed to the screen, modify your script file to suppress that output.
3
ANALYSIS AND GRAPHING IN MATLAB
One of MATLAB’s greatest strengths is in handling large datasets. A particular benefit to
oceanographers and meteorologists is its ability to perform mathematical operations on
gridded datasets. Let’s look at a couple of simple examples.
Go to http://www.esrl.noaa.gov/psd/data/gridded/reanalysis/. This page, maintained by
NOAA, contains gridded data sets (known as re-analyses) that may be quite useful to you
during the next four semesters at USNA. A “reanalysis” is a gridded dataset that takes all
available observations (satellite, surface, buoy, radiosonde, aircraft), including observations
that may not have been available in real-time (hence “re”analysis), and blends them together
in a gridded form. In Lab 1, we are going to look at data from NCEP/DOE Reanalysis II.
Click through to the Surface Data, Mean Sea Level Pressure daily mean. Click the image
icon, “create plot/subset”. Again click the image icon “Make plot or subset” under Daily
Mean. Again, this is a neat tool to plot high-quality meteorological (and oceanographical, if
you choose a different data set besides NCEP/DOE Reanalysis II) data. Leave the dimensions
alone, but change the time to the I-Day of the Class of 2016 (your first day of plebe summer).
We want to see the global sea level pressure field for that day. Change the plot output options
to “Plot on a white background”, “Contour Fill”, and Scale the plot to 175%. You should get
something like this:
Fig. 2: Mean sea level pressure for 28
Jun 2012, from NOAA NCEP/DOE
Reanalysis II.
(10 pts) Write a few sentences discussing this figure. Pretend you are presenting it to your
company officer, who is a scientist but did not major in oceanography or meteorology. Orient
him/her to the figure and then highlight a few of what you consider to be the more important
features in the figure. Be sure to comment on the units, too.
4
Now, we are going to reproduce this figure in MATLAB. Save the following data in your
MATLAB working directory. http://www.usna.edu/Users/oceano/barrett/SO335/lab1.mat
In your Lab1_xxxxx.mat script, a few lines down from the first part of the lab, type the
following
% Now analyze NCEP/DOE Reanalysis II sea level pressure data
clear all
close all
load lab1.mat
Execute the script file. Take a moment to look at the variables that loaded into the workspace
as a result of loading lab1.mat. There should be four variables:
Name
Size
Bytes
Class
coastline
lat
lon
mslp_25Dec2013
mslp_28Jun2012
61632x2
73x1
144x1
73x144
73x144
986112
584
1152
84096
84096
double
double
double
double
double
Attributes
Variables lat and lon are one-dimensional, and lat has 73 values and lon 144 values. Variables
mslp_28Jun2012 and mslp_25Dec2013 are two-dimensional, with 73 rows by 144 columns.
We’ll come back to the variables coastline and mslp_25Dec2013 later in the lab. The current
goal is to reproduce the figure made by NOAA for the 28-Jun-2012 sea level pressure data.
To plot this data, we need to do a few things. First, activate a figure window (if it’s not
already open, MATLAB will open it up). Second, clear that figure window. Third, create two
gridded latitude and longitude variables: that is, for each point on the figure from NOAA, we
want to know both the latitude AND longitude. Here’s how to do these three things (add
them to your script):
figure(1)
clf
[xgrid,ygrid] = meshgrid(lon,lat);
(5 pts) What is the shape of the resulting variables, xgrid and ygrid? How does their shape
compare to the variables lon and lat? How does the shape of xgrid and ygrid compare to the
shape of mslp_28Jun2012?
Go into the MATLAB command window. Double-click on the variable xgrid. In the
window that appears, MATLAB shows all of the longitudes for the grid that corresponds to
the figure we are about to create.
5
(5 pts) What is the longitude of the first grid point in the y-direction? What about the
longitude of the last grid point in the y-direction? How many grid points are there in the xdirection?
Now, do the same for the variable ygrid.
(5 pts) What is the latitude of the first grid point in the y-direction? What about the latitude
of the last grid point in the y-direction? How many grid points are there in the y-direction?
(5 pts) Look at the variables xgrid and ygrid in the MATLAB variable editor. What longitude
corresponds to row 18 column 32? What latitude corresponds to row 18 column 32?
If you wanted to know the longitude and latitude for the grid cell (18,32), there is a much
easier way to do it than scrolling around in the editor window: Go to the command window
and, at the prompt, type
xgrid(18,32)
ygrid(18,32)
Now that we have the gridded latitudes and longitudes defined, let’s plot the sea level
pressures for 28-Jun-2012. Add the following lines to your script and run it.
contourf(mslp_28Jun2012)
colorbar
title('Mean sea level pressure (pascals) on 28 Jun 2012. XXX')
**Note that your initials need to replace “XXX” in the figure title (a practice that we will use
only for this course; other USNA / Oceanography instructors have different preferences).
You should get something that somewhat resembles Fig. 2. The function contourf produces
filled contours of the variable mslp_28Jun2012. The colorbar function adds the colorbar to
the figure (default location is to the left, although there are many other spots you can put it).
The title function adds the title (note that you have to put the title in quotes. Single quotes are
MATLAB’s way of differentiating between strings (a fancy word for text) and variables. A
quick aside: you could be fancy with your title, and create a variable first, then produce the
title from that variable, e.g.
6
titlename = 'Mean sea level pressure (pascals) on 28 Jun 2012. XXX';
title(titlename)
Fig. 2: Mean sea level pressure for 28 Jun 2012.
Back to the figure: notice the x- and y-axes: they do not yet have latitude or longitude
information on them. That is because we haven’t yet told MATLAB what they are. Let’s do
that now, but in a new figure window. Just to make sure you’re following, the second part of
your script should look like this:
% Now analyze NCEP/DOE Reanalysis II sea level pressure data
clear all
close all
load lab1.mat
figure(1)
clf
[xgrid,ygrid] = meshgrid(lon,lat);
contourf(mslp_28Jun2012)
colorbar
title('Mean sea level pressure (pascals) on 28 Jun 2012. XXX')
Add the following to your script:
figure(2)
clf
[xgrid,ygrid] = meshgrid(lon,lat);
contourf(xgrid,ygrid,mslp_28Jun2012)
colorbar
title('Mean sea level pressure (pascals) on 28 Jun 2012. XXX')
7
Run the script. Compare figures 1 and 2.
(5 pts) What are the differences between figures 1 and 2? Why are the two figures different?
The final steps are really aesthetic ones: Let’s force MATLAB’s colors to match those of the
NOAA web site, change the units from pascals to millibars, labels to the x- and y-axes, and
add continental backgrounds.
To change colors: NOAA uses “GrADS” software to create the figure on the web site. The
default colorbar that it uses http://www.iges.org/grads/gadoc/16colors.html is different from
MATLAB’s. The easiest way to get the colors we want is to type them ourselves, in “redgreen-blue” format (RGB format). Using the information in the web site about GrADS, we
see that we need to define a 13-row, 3-column variable (the columns are red, green, and blue,
and the rows are the colors that result from that particular RGB combination. Interesting, even
Powerpoint, Word, Excel, etc allow you to define colors using RGB codes). Type (or paste)
the following into your script
grads_colors = [
160 0 200
110 0 220
30 60 255
30 60 255
0 160 255
0 200 200
0 210 140
0 220 0
160 230 50
230 220 50
230 175 45
240 130 40
250 60 60
240 0 130]/255;
Now we can use the function colormap to force there to be 13 colors, with the RGB
combinations we just defined. Type the following in your script (you can add it to figure 2):
colormap(grads_colors)
Run the script again. You should get something that looks pretty close to the figure on
NOAA’s web site.
8
To change from pascals to millibars, we need to know the unit conversion factor.
(5 pts) What is the unit conversion factor from pascals to millibars?
In your script, store the conversion factor as a variable, and multiple (or divide) the pressure
variable by it (you must put a number after the equals sign!)
conv_factor =
To add labels to the x- and y- axes, simply add the commands
xlabel('longitude')
ylabel('latitude')
Your figure 2 section should now look like
figure(2)
clf
contourf(xgrid,ygrid,mslp_28Jun2012./conv_factor)
colorbar
title('Mean sea level pressure (mb) on 28 Jun 2012. XXX')
cmap(grads_colors)
xlabel('longitude')
ylabel('latitude')
Do the results make sense? (If not, you probably made a mistake with the unit conversion
factor).
Finally, to add the coastlines, we need to plot a series of lines that define the coast.
Fortunately, there are Geographical Information Systems (GIS) shapefiles that contain lat/lon
pairings of all global coastlines. We’ll use a basic one here, since we don’t need highresolution detail. NOAA maintains a coastline data base at http://www.ngdc.noaa.gov/
mgg_coastline/. The coastline data are already downloaded for you and stored in the coastline
variable you loaded as a part of Lab1.mat.
Add the following lines to your figure(2) code:
hold on
line(coastline(:,1),coastline(:,2),'color','k')
9
(5 pts) What does the command “hold on” do? What do each of the four parts (separated by
commas) of the line command instruct MATLAB to do?
The last part of this lab: differences. MATLAB is fantastic at performing mathematical (and
statistical, and trigonometric, etc.) operations on large data sets. Remember when you loaded
the data from the SO335 course web site, you loaded two pressure files: one for 28 June 2012
(your I-day), and one for 25 Dec 2013.
(15 pts) Modify your script to contour-fill sea level pressure for 25 Dec 2013, and plot that
data in Figure 3 window. It should look identical to the NOAA web site. Add appropriate
titles, axes labels, and coastlines.
(15 pts) Create a contour-filled plot of the difference in sea level pressure from 25 Dec 2013
and 28 Jun 2012. Put the plot in Figure 4 window. Subtract the old from the new (so 25 Dec
minus 28 Jun). Add appropriate titles, axes labels, and coastlines.
.
Deliverables: For this lab, you must turn in: (1) the 10-pg lab exercise (with answers given to
questions marked with point values), (2) your printed MATLAB code, and (3) print-outs of
10
Download