22
1 GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB MATLAB is a contraction of “Matrix Laboratory”, and as you'll soon see, matrices are fundamental to everything in the MATLAB scientific computing environment. This program is quick for doing simple things, and incredibly extensible for doing more involved things – it can be a simple calculator, a data visualization tool, an advanced programming language, and everything in between. In this course we'll cover just a few ways that MATLAB can be used in Earth science applications, but keep in mind that this tool is limited only by the user's creativity. If you haven’t been exposed to programming before, the whole concept may seem daunting, but take comfort in the fact that MATLAB is the most gentle and forgiving way to become familiar with programming. If there's one application that every Earth scientist should know, this is it. Command Window & Environment Really, there's no better way to get acquainted with your new best friend, than to dive right in – here's what you'll see (almost) when you first open MATLAB.

GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

1

GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB MATLAB is a contraction of “Matrix Laboratory”, and as you'll soon see, matrices are fundamental to everything in the MATLAB scientific computing environment. This program is quick for doing simple things, and incredibly extensible for doing more involved things – it can be a simple calculator, a data visualization tool, an advanced programming language, and everything in between. In this course we'll cover just a few ways that MATLAB can be used in Earth science applications, but keep in mind that this tool is limited only by the user's creativity. If you haven’t been exposed to programming before, the whole concept may seem daunting, but take comfort in the fact that MATLAB is the most gentle and forgiving way to become familiar with programming. If there's one application that every Earth scientist should know, this is it. Command Window & Environment Really, there's no better way to get acquainted with your new best friend, than to dive right in – here's what you'll see (almost) when you first open MATLAB.

Page 2: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

2

This has been annotated with red text to identify the basic layout (fully customizable to your liking). Let's first concern ourselves with the command window, as this is where the action is. Often you will work at the command line in the command window. The command window allows you to type commands directly and see the results immediately. For example at the >>, define a variable "a" by typing: a=[1 2 3 4 5] *alternatively, you could do this with the 'linspace' command, or just by defining it with min/interval/max, like so: a=(1:1:5) What is printed out below is the output of the command. Now create another variable "b" by typing: b=[6 -3 4 2 -7] You've just created two matrices (or vectors if they are just one row or column). Wanna add or subtract them? just type: a+b (or a-b, as the case may be) The result, obviously, was the vector product (or difference) – the resulting matrix has the same dimensions as the component matrices, and displays the sum (or difference) of the individual matrix elements. You could have also stored the result as a new matrix "c" by typing: c=a+b Now we'll get visual. To see what you've created, at the command prompt type: plot(a,c) This is just telling MATLAB to create a simple line plot of the vector c as a function of the vector a. Nice and simple. One more little twist, we can perform operations on matrices (vectors) like so: d=exp(c/10) Here we created vector "d" by making the calculation: d=e(c/10). Wasn't that fun?

Page 3: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

3

Data Types – Scalers vs. Vectors vs. Matrices vs. Strings vs. Structures Data is handled in several ways in MATLAB. In the few lines of code above, you created and manipulated several vectors (a.k.a. arrays). These are variables whose dimensions (lengths of rows and columns, respectively) are m x 1 or 1 x n, considering m and n to be any real positive integer. A matrix is an m x n vector. Similarly, a scalar is a 1 x 1 array. You can always change one or more elements in a vector or matrix, by identifying the location (row and column) of the element(s) in question, and reassigning its value. For example, if we wanted to change the 2nd element of matrix "b", defined above from a value of -3, to a value of -4, we simply type: b(1,2)=-4 All that did was identify the position of row 1 and column 2 in the 1 x 5 matrix "b", and re-establish it's value as -4. This can be done with entire rows or columns, by using the colon ":". *along the same lines, what if you had a variable that was 4 rows by 5 columns, and you wanted to re-assign a separate variable name to one of the columns? Here's how you go about it. First, create a 4 x 5 matrix: f=rand(4,5) now, assign the 3rd column to be a separate variable named g: g=f(:,3) The colon (:) means "all rows of" and the 3 refers to the 3rd column. A string is a chunk of data that is in text format rather than having numerical values. The following creates a string: >> x=['This class is just super.'] x = This class is just super. If you enter letters or numbers in single quotes, as above, they become strings and take on no numerical value – sometimes this can be quite valuable in programming. Data structures can be thought of as multi-dimensional matrices with names to identify fields rather than row and column numbers. These can be incredibly powerful but hold off on examples with structures right now – we’ll revisit them later.

Page 4: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

4

Getting Help MATLAB has an incredibly good help system. The help is built into MATLAB and can be accessed from the help menu (also the full help documentation is available online at mathworks.com). Because this help is so good, it is silly to reproduce everything here. We show some brief descriptions on commands below, but we expect you to READ THE HELP FILES. To get help on a command, type "help commandname" or "doc commandname" in Command Window where commandname is the command of interest. For example, typing: >> help plot provides the detailed instructions found in the "plot" command, whereas: >> doc plot opens a separate help viewer window and gives the detailed documentation/examples, shown below.

Page 5: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

5

MATLAB's help documentation will basically be the best reference or textbook you could ask for in this class. Writing an m-file We'll return to the Command Window later, as it is often the first place you go to try out new commands, but for now we'll introduce the Editor Window, which is where you will write your first m-files (with a .m extension), a.k.a. your first "programs". The MATLAB Editor is nothing more than a simple text editor (e.g. Notepad or Wordpad (windows), TextEdit or TextWrangler (mac), and vi or emacs (unix), just to name a few). You are free to use any text editor you choose, but the MATLAB editor has some cool features, which are handy for writing m-files or functions. When you write an m-file, you are really just storing a bunch of sequential commands that could just as easily be typed at the >> (prompt) in the Command Window, but once you store them in an m-file, you can just run the m-file, rather than re-typing each command individually, every time you want to perform a series of mathematical operations. Like a macro in Excel, this really saves time. Here's one by me – read what I've got in there:

The above m-file results in the following plot:

Page 6: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

6

Now, try to write an m-file that creates the 1 x 5 matrix (number of rows x number of columns, as is the MATLAB convention), that you built by matrix addition above (matrix "c") and plots it against matrix "a". Give the m-file a name and save it with the .m extension. Here's a tip – start your m-file with the "clear" command (see the help), this will give you a clean slate before your m-file is executed. Once the program is saved you can just type the name of the file and all of the commands will execute. For now, be sure to have your working directory (try "help pwd") be the same as the directory in which you saved your m-file (we can change this later with the "path" command). What I do when writing a new m-file, is try a series of commands at the command line, then copy them from the Command History and paste them into an m-file. This way, I can be sure that each command works the way I want it to. By the way...To get a list of currently defined variables You can always find out what you've got goin' on in MATLAB by typing 'whos'. This will list all of the known variables and some details about them – to delve further, just type the name of the variable at the command line. Also, if you are into the Excel-style thing, you can double

Page 7: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

7

click on a variable name in the workspace window and it will open the "Array Editor", which enables you to examine the contents of every cell in a matrix. Writing a function While m-files are very easy to create, they are just a bit limiting because they occupy MATLAB's global memory. A better way to program in MATLAB, (trust me) is to create functions. You're already familiar with MATLAB functions, as every command is simply a function that is based on other functions and written (in an exhaustively general way) by some geek at MATLAB central. Now we'll re-tool our m-file that we wrote above, as a general function. Functions are ways to make your code general for use over and over again on multiple different data sets for example. See the documentation on Functions and we'll walk through it together in class.

Then you "call" the function from the command line (or within another m-file) by: >> [c,d]=sample_function(a,b) making sure that "a" and "b" are already defined. The function temporarily renames a, b, c, and d, while executing, then returns the results as if no funny business ever occurred. You can see how it might not always be convenient to name variables so inflexibly – functions can really save our tails, in this regard. Working in a Directory & Your Path MATLAB is (thankfully) specific about “where” you are working (i.e. in which directory). To find out where you are working right now, type pwd. It will probably respond with something that looks like this: >> pwd ans =

Page 8: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

8

/Users/pna/Documents/MATLAB At first, you’ll find it easier to work in the same directory when getting familiar with MATLAB – this way any .m files you write will be visible to MATLAB. In the future, however, after you’ve built a substantial library of your own MATLAB .m files, you’ll want to add directories to your path. Your path is a list of directories (folders) that you’d like MATLAB to be able to readily access every time you sit down to work. We can come back to this later. By the way...Repeating commands and command completion You can always retrieve previous commands you have executed by pressing the up arrow or by typing the first letter of the command and then pressing up arrow. You can save any command by copying it from the command window and pasting it into an editor window. Saving this as a m-file allows you to repeat the command anytime you type the name of the file in your command window. Also, if you know that the command you want begins with a certain letter or certain few letters, you can just type the first couple letters and hit tab. This will bring up a list to choose from. Worked Example Ok, now we're going to work through an exercise in data treatment, by using an example from Gerry Middleton's book (reference below). First, obtain the sample data set from our course website: The data file (called dewijs.dat) is in ascii text format, which makes things easy. Once you copy it to your working directory, you can load it into the current workspace by typing: >> load dewijs.dat Here's Middleton's excerpt on how to handle the data:

Page 9: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

9

Page 10: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

10

Page 11: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

11

Page 12: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

12

References In my opinion, the best reference for MATLAB is the help documentation included with the program – it usually gives some good examples of how to use a command in concert with other commands. Additionally, you'll learn a lot just by scanning the web for m-files and functions that others have written – again, learning by example often works best. If you're hungry for more MATLAB reading material, here are some recommendations (with my comments), but I have not seen everything out there, and there's always some engineer coming out with a new MATLAB book. Pratap, Rudra, 2005. Getting Started with MATLAB 7: A Quick Introduction for Scientists and Engineers, Oxford University Press, USA.

* I have the edition of this book that went with MATLAB 4, but found it very useful – don't know if the latest edition is good or not.

Middleton, Gerard V., 1999. Data Analysis in the Earth Sciences Using MATLAB, Prentice Hall.

* oops, this one is out of print, but if you'd like to borrow my (or John's) copy to Xerox, you may. It's pretty good for what we're doing in this course, as it was written by a geologist (a rather famous one at that), but it is focused mostly on the statistical applications of MATLAB.

Hanselman and Littlefield, 2004. Mastering MATLAB 7, Prentice Hall.

* This book is fine, but not much more than the help documentation can provide – if you want a portable version of that, then this might do the trick.

You should also rely on your Googling skills – documentation for most MATLAB commands (or even other people's codes) are available from obscure websites. This can be extremely quick and effective.

Page 13: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

13

Appendix – List of Basic Commands As an appendix to the first lesson here, I've inserted some pages from the end of Pratap's book. These pages include a pretty good list of MATLAB commands to get you going – remember, to get more complete documentation on any of the commands, just type "help " then the command name.

Page 14: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

14

Page 15: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

15

Page 16: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

16

Page 17: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

17

Page 18: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

18

Page 19: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

19

Page 20: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

20

Page 21: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

21

Page 22: GLY 6932 - Geostatistics Fall 2011 Lecture 2 ...users.clas.ufl.edu/.../GeoStats_Lec02.pdf · GLY 6932 - Geostatistics Fall 2011 Lecture 2 – Introduction to the Basics of MATLAB

22