MATLAB Tutorial

advertisement
GEOG 401 – MATLAB TUTORIAL
In this tutorial, you will be introduced to the MATLAB Desktop and given a fast
overview of how to interact with MATLAB. Don’t worry about understanding
everything or having to remember all the commands. This tutorial is a reference,
too.
You will also start on Assignment #1 of Adopt a Climate Station, but we need to give
you some basics of MATLAB first.
Start MATLAB in Windows by clicking the MATLAB R2012b icon on your desktop
Some additional files for this tutorial are at:
http://webpages.uidaho.edu/jabatzoglou/CLASSES/GEOG401/MATLAB.html
_________________________________________________________________________________________________
Current Folder
This is the directory where you can save your work.
TASK: Change the current folder to the Desktop
Command Window
This is where you type the commands or instructions into MATLAB.
You type or paste your inputs after the >>
You can enter more than one line at a time.
Type enter to have MATLAB execute the commands
_________________________________________________________________________________________________
_________________________________________________________________________________________________
MATLAB as a calculator
Enter the following after the MATLAB prompt >> (then hit enter to execute)
1+1
If you do not assign your expression to a variable, MATLAB sets it to a variable
named ‘ans’. Try
ans +5
What happens when you enter a semicolon at the end of the line?
5+5 ;
The following are ways to use MATLAB as a calculator
10^2
%exp(1)
log10(10)
% sin(pi/2)
abs(-4)
floor(4.5)
%ceil(4.5)
min(4,6)
%max(4,6)
_________________________________________________________________________________________________
Creating, Using, Clearing Variables
Copy/paste the following into MATLAB:
x = 5;
y=7;
z=x+y
Note that these variables show up in the ‘workspace’. Try these one at a time:
x=10;
%this overwrites your previous value of x
clear x
%this clears only x from the workspace
clear all
%this clears all variables from the workspace
_________________________________________________________________________________________________
______________________________________________________________________________________________
Getting Help
MATLAB ERROR MESSAGES: learn to read the error messages that return
FUNCTION HELP: If you know the function you need help with, inside MATLAB type
>>help <command> (i.e. help plot)
This is also available at the MathWorks Documentation Center:
http://www.mathworks.com/help/
TOPIC HELP: If you need topic help, you can search the Newsgroups on the
MathWorks website. Here, MATLAB employees answer user questions:
Newsgroups: http://www.mathworks.com/matlabcentral/newsreader/
HELP!: If you don’t know what function to use or how to use MATLAB, ask your
question in a google search. Your answer is on the internet somewhere!
_________________________________________________________________________________________________
Creating Arrays
Arrays are grids of numbers.
Try the following:
c=5
size(c )
%this creates a point grid of number
%a constant (0-D array)
X = [0 1 2 3]
X = [0,1,2,3]
%this creates a 1-D row of numbers
%
%(separate columns by spaces or commas)
%this is a row vector (a 1-D array)
size(X)
length(X)
A= [ 1 2 3 ; 4 5 6; 7 8 9 ]
A=[1 2 3
456
7 8 9]
%this creates a 2-D grid of numbers
size(A)
%
%(separate rows by semicolons ; or returns)
%this is a marix (a 2-D array)
B=[A A]
B = [A;A]
%help repmat
%2 matrix A’s in a row
%2 matrix A’s in a column
% repeating a pattern (future reference)
What does the workspace say about c,X,A?
______________________________________________________________________________________________
Special Arrays
There are MATLAB functions to create special arrays. Try some of the following:
X = [0:2:10]
%equally spaced row vector
X =linspace(0,10,6) % this uses a function to do the same
A = ones(5)
A = zeros(5,2)
A = eye(5)
A = nan(5)
A=randn(5)
A=rand(2,2,2)
%this is the identity array
%array of normal random numbers
%array of uniform random numbers on [0,1]
_____________________________________________________________________________________________
Creating, Saving Figures
Creating figures:
%help plot
tempF=[30 32 35 40]; tempC=(tempF-32)/1.8;
plot(tempC,tempF);
%Try the variants
plot(tempC,tempF, 'x');
title('text')
plot(tempC,tempF, 'rx');
plot(tempC(1:3),tempF(1:3));
%this only plots a subset of the data
%Add titles and labels
title('Temperature (F vs C) ')
xlabel('Degrees C')
ylabel('Degrees F')
%Other
hold on
axis tight
Clearing figures
clf
%allows you to overlay another plot on current plot
%removes white space from plot
%clears figure
Saving figures
From the command window,
print('myfilename.jpg', '-djpeg'); %jpg file
print('myfilename.tif', '-dtiff');
%tiff file
Manually from the File Menu, select Save As…Select a file type
.fig: MATLAB graphics format
.*jpg,.*tiff : best formats to be compatible with other software
Copying figures
From the Edit Menu, select Copy %this copies figure to the clipboard
Open other software (i.e. MS Word) and paste from clipboard to document
_____________________________________________________________________________________________
______________________________________________________________________________________________
Writing, Calling, Debugging Scripts
When you exit MATLAB, your command history will disappear. A way to save your
command history is to copy all of your MATLAB commands in an M-File as a script
and save that. You can execute this script at any time, including next time you open
MATLAB.
WRITING:
You create an M-file, by going to New Script
Copy your commands into the file and then save your file with a .m extension.
It is a best practice to write a script for each of your assignments. As you
work on it, you can edit this script and run either pieces of it or the whole
thing. This script serves as a reminder to you as to what you did for each
assignment.
Write comments to yourself so you can read your code later
Comments start with %
CALLING:
There are two ways to execute scripts:
1. Copy and paste pieces of the script to the command line >>
2. Execute the entire script by typing the name of the script at the
command line
>>SampleScript
DEBUGGING:
Either it runs perfectly or there are errors
If MATLAB displays an error message , you will need to fix the file.
 Make sure that SampleScript.m is in your Current Directory in MATLAB
 The error output identifies which line has a problem. Go to that line.
 Check the syntax on your command on that line and fix it.
 Save the file
 Re-execute the script
Note: after running a script, all of the script variables show up in the ‘workspace’
______________________________________________________________________________________________
_______________________________________________________________________________________________
Calling and Writing Functions
CHECK THE FUNCTION SYNTAX
To find out how to use the function, type ‘help <command>’
help mean;
CALLING FUNCTIONS:
Follow the syntax of the function
X = rand(5,1)
Y=mean(X)
Functions written by users can also be called the same way.
WRITING FUNCTIONS:
Click on the button New … Function
This gives you the basic template of a function.
Copy and paste the following over the entire template:
function [dataC] = convertFtoC(dataF);
dataC = (dataF-32)/1.8; %converting data in F to data in C
end
Save the function to the Current Directory as convertFtoC.m
You call the above function the same way as other functions
tempF=[32 35 37 40];
[tempC]=convertFtoC(tempF);
_______________________________________________________________________________________________
_______________________________________________________________________________________________
Saving,Loading Data
SAVING/LOADING .mat data
Download the SampleData.mat file from the website.
Place it in the Current Directory of MATLAB.
You’ll see it show up in the Current Folder. Click on it… or type
load SampleData;
%.mat is not needed
You can save your data as a .mat file by typing
save myfilename.mat %saves entire workspace (not commands though)
save myfilename.mat x y %only saves variables x,y
LOADING (other kinds of data)
Enter by hand (only feasible for very small data sets)
Copy and paste method
For some data, you might be able to copy it and just paste it into MATLAB.
Copy the following data:
1898,0.53,0.64,1.10,-408.12,1.91,0.63,0.17,0.03,0.09,0.28,3.62,0.89
1899,1.49,0.67,3.08,1.23,0.72,0.02,0.00,0.44,0.15,1.66,1.63,1.75
1900,1.30,0.72,0.42,0.57,0.62,0.78,0.02,0.35,0.49,2.02,0.52,-408.12
At the MATLAB prompt, type:
A=[
paste the data and then enter another
]
Loading .csv data
Download the SampleData.csv file from the website.
Place the file in the Current Directory of MATLAB.
Look at the contents of the file. Notice that the data doesn’t start until line 5.
We could delete lines 1-4 from the data, but it’s nice to keep this information
with the file or it could get lost.
We can use csvread to read in the data
data = csvread('SampleData.csv',4,0);
Note that here …. 4=row 5 …. and ….. 0=column 1
Then we need to extract the data from this array (see manipulating arrays)
You’ll need to extract years and T,P from this data;
Years = data(:, 1);
%this extracts all rows, first column
T = data(:,2:12);
%this extracts all rows, columns 2-12
Import data button
The MATLAB desktop has an easier manual way to download different kinds
of data: Click the Import Data button and follow directions.
_____________________________________________________________________________________________
Manipulating Arrays
In MATLAB, you’ll want to do operations on your arrays.
Before starting on the assignment, explore some operations using
Subsetting Arrays
A= [ 1 2 3 ; 4 5 6; 7 8 9 ]
A(2,3)
%indexing: getting a single entry row 2, column 3
A(2,1:2)
%block operator: getting row 2, columns 1:2
A(2,: )
%colon operator: getting row 2, all columns
A(:,1)
%colon operator: getting column 1, all rows
A(:)
%what does this one do?
Replacing Values
A = ones(5); B=2*ones(5);
A(2,:) = B(2,: );
%assign a subset to other values
help find
f=find(A==2); A(f) = 3;
f=find(A==2); A(f) = B(f);
%use the find command
%this replaces the 2’s with 3’s
%this replaces the 2’s w/contents from B
Component-wise operations
A = ones(5); B=2*ones(5);
5*A
%multiplying components by 5
A+B
%add the components of each vector
B.^2
%square the components of the array
A.*B
%multiply the components of each array
A./B
%divide the components of each array
1./B
%takes 1 divided by components of the array
Matrix operations
A= [ 1 2 3 ; 4 5 6; 7 8 9 ]
B=A'
%transposing
A = ones(5); B=2*ones(5);
A*B
%matrix multiplication
Changing the size of an array (advanced commands for future reference)
%help permute
%help reshape
%help squeeze
___________________________________________________________________________________________
‘Adopt a climate station’ #1 (Process Data)
Download station data for temperature and precipitation
 Go to http://www.wrcc.dri.edu/wwdt/time/
 In the middle, select “United States Historical Climatology Network Stations”
 On the right side, select “All Months”
 Pick your station
 Select either Temperature or Precipitation (note: Temp has an error)
 Some of the data may be -9999 (missing values)
 Copy and paste this comma-separated-data into a text editor(Start… Utilities..
Notepad)
 Save it to your Current Directory as stationdata.csv
 Load this data into MATLAB using temp =csvread(‘filename.csv’,4,0);
 Extract variables from this using:
o Years = temp(:,1);
o T = temp(:,2:13); %or P=temp(:,2:13);
Download estimates for the -9999 values
 Go to http://www.wrcc.dri.edu/wwdt/time/
 In the middle, select “Single 4x4km pixel from gridded dataset
 On the right side, select “All Months”
 Enter the lat/lon of your station.
 Select either Temperature or Precipitation
 The values reported are actually estimated values from stations around the
indicated lat/lon.
 Copy and paste to a file stationdata_estimates.csv
 Load and extract data the same way as before.. but call them T_est, P_est.
_________________________________________________________________________________________
In Class Substitution for the above tasks of the assignment:
Since the http://www.wrcc.dri.edu/wwdt/time/
is not working for retrieving temperature data (you should try the process to
get precipitation data, though), instead….
o Download the file SampleData.mat from John’s website:
http://webpages.uidaho.edu/jabatzoglou/CLASSES/GEOG401/MATLAB.html
o Load this file into matlab by clicking on it and seeing the variables in the
o
workspace.
This file has T,P and years in it. T and P are in units of F and inches.
___________________________________________________________________________________________
You’ll have to deal with the missing values (-9999) somehow.
Either delete the -9999s in the original data file or do the following:
f=find(T ==-9999);T(f) = estT(f);
___________________________________________________________________________________________
___________________________________________________________________________________________
Convert units to scientific units.
T=convertFtoC(T);
%Convert from F to C
%Write a new function to convert P from inches to mm and use it
%Save your data
save myTPdata T P Years %creates a file called myTPdata.mat
%see the file myTPdata.mat in the Current directory. Click on it and see that it has
all the variables you expect it to have.
___________________________________________________________________________________________
___________________________________________________________________________________________
‘Adopt a climate station’ #1 (Analyze Data)
1. Create a script to perform tasks (Assignment #1, Tasks 5-8 ).
 Load in T,P,Years data
 Calculate climate normals and anomalies
 Create climographs
___________________________________________________________________________________________
%Load in T,P,Years dat
load myTPdata
%or click on myTPdata.mat in the Current Directory
%Calculate monthly climate normals for 1981-2010
%find indices corresponding to 1981-2010.
yr_indices=? … something like 86:116;
%check that you did this right with
years(yr_indices)
%this should be 1981:2010
% find mean of monthly data over all years (the first dimension)
Tnormal=mean(T(yr_indices,:), 1 );
Pnormal=mean(P(yr_indices,:), 1 );
%Create a climograph of monthly T/P normals
%Download the climograph.m file from John’s website
figure(1)
climograph(Tnormal,Pnormal);
%save figure (manually or use save command)
%Create a climograph of monthly T/P using only 2012 data
%find index corresponding to year 2012
%yr_2012 = ? … %should be around118
%check that you did this right with
%years(yr_2012)
figure(2)
climograph(T(yr_2012,:),P(yr_2012,:))
%save figure (manually or use save command)
%Calculate monthly anomalies for 2012
Tanom = myTData(yr_2012,:) –Tnormal % differences from normal (for T)
Panom = myPData(yr_2012,:)./Pnormal %percent of normal (for P)
%either graph these for your report… or put in a table….’report’ these somehow.
___________________________________________________________________________________________
Download