GLY Geostatistics Fall Lecture 2 Introduction to the Basics of MATLAB. Command Window & Environment

Similar documents
Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia

You just told Matlab to create two strings of letters 'I have no idea what I m doing' and to name those strings str1 and str2.

Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion of this lesson)

Week - 01 Lecture - 04 Downloading and installing Python

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

(Ca...

Intro To Excel Spreadsheet for use in Introductory Sciences

Exploring extreme weather with Excel - The basics

Part I: MATLAB Overview

Physics REU Unix Tutorial

Getting To Know Matlab

MATLAB TUTORIAL WORKSHEET

Introduction. Matlab for Psychologists. Overview. Coding v. button clicking. Hello, nice to meet you. Variables

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

Matlab Tutorial 1: Working with variables, arrays, and plotting

Matlab Introduction. Scalar Variables and Arithmetic Operators

Lab 1: Setup 12:00 PM, Sep 10, 2017

Matlab = Matrix Laboratory. It is designed to be great at handling matrices.

Azon Master Class. By Ryan Stevenson Guidebook #5 WordPress Usage

Lab1: Communicating science

Ruby on Rails Welcome. Using the exercise files

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

MATLAB Project: Getting Started with MATLAB

MATLAB. Miran H. S. Mohammed. Lecture 1

Where Did My Files Go? How to find your files using Windows 10

Excel Primer CH141 Fall, 2017

EOSC 352 MATLAB Review

Introduction to MATLAB

Microsoft Excel 2007

MITOCW watch?v=kz7jjltq9r4

Introduction to MATLAB

EGR 111 Introduction to MATLAB

Creating Word Outlines from Compendium on a Mac

Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122

ECON 502 INTRODUCTION TO MATLAB Nov 9, 2007 TA: Murat Koyuncu

Solar Campaign Google Guide. PART 1 Google Drive

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

VIDYA SAGAR COMPUTER ACADEMY. Excel Basics

Chapter One: Getting Started With IBM SPSS for Windows

Depending on the computer you find yourself in front of, here s what you ll need to do to open SPSS.

Running Wordstar 6 on Windows 7 Using vdos

2: Functions, Equations, and Graphs

MITOCW ocw f99-lec07_300k

Interface. 2. Interface Adobe InDesign CS2 H O T

ECE 3793 Matlab Project 1

The first thing we ll need is some numbers. I m going to use the set of times and drug concentration levels in a patient s bloodstream given below.

Script for Interview about LATEX and Friends

Basic Unix and Matlab Logging in from another Unix machine, e.g. ECS lab Dells

Introduction to the workbook and spreadsheet

When you first log in, you will be placed in your home directory. To see what this directory is named, type:

6.001 Notes: Section 8.1

Introduction to Scientific Computing with Matlab

Introduction to MATLAB

Getting Help...71 Getting help with ScreenSteps...72

Google Docs Website (Sign in or create an account):

How to Use Google. Sign in to your Chromebook. Let s get started: The sign-in screen.

HOW TO EXPORT BUYER NAMES & ADDRESSES FROM PAYPAL TO A CSV FILE

Slide 1 CS 170 Java Programming 1 Testing Karel

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

The Foundation. Review in an instant

DOWNLOAD PDF EXCEL MACRO TO PRINT WORKSHEET TO

Computer Vision. Matlab

WHAT IS MATLAB?... 1 STARTING MATLAB & USING THE COMMAND LINE... 1 BASIC ARITHMETIC OPERATIONS... 5 ORDER OF OPERATIONS... 7

Chapter 2. Editing And Compiling

CITS2401 Computer Analysis & Visualisation

Introduction to MATLAB

! Emacs Howto Tutorial!

Tracking changes in Word 2007 Table of Contents

An Introduction to Maple This lab is adapted from a lab created by Bob Milnikel.

Chapter 1. Getting Started

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

CS1114: Matlab Introduction

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

McTutorial: A MATLAB Tutorial

Getting Started With Linux and Fortran Part 2

Operating System Interaction via bash

Mastering the Actuarial Tool Kit

Office Hours: Hidden gems in Excel 2007

How to Improve Your Campaign Conversion Rates

TABLE OF CONTENTS CHANGES IN 2.0 FROM 1.O

SLACK. What is it? How do I use It?

GIS LAB 1. Basic GIS Operations with ArcGIS. Calculating Stream Lengths and Watershed Areas.

C++ Algorithms For Digital Signal Processing (2nd Edition) Ebooks Free

Introduction to MATLAB

Light Speed with Excel

Using Microsoft Excel

1 Introduction to Matlab

Creating Vector Shapes Week 2 Assignment 1. Illustrator Defaults

Intro. Scheme Basics. scm> 5 5. scm>

The Mac OS X Command Line: Unix Under The Hood Ebooks Free

A Brief Introduction to Matlab for Econometrics Simulations. Greg Fischer MIT February 2006

QUICK EXCEL TUTORIAL. The Very Basics

MATLAB Project: Getting Started with MATLAB

EE3TP4: Signals and Systems Lab 1: Introduction to Matlab Tim Davidson Ext Objective. Report. Introduction to Matlab

Alternate Appendix A: Using the TI-92 Calculator

How to program with Matlab (PART 1/3)

Transcription:

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. 1

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? 2

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 2 nd 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 reestablish 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 3 rd column to be a separate variable named g: g=f(:,3) The colon (:) means "all rows of" and the 3 refers to the 3 rd 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. 3

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. 4

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: 5

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 6

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 = 7

/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: 8

9

10

11

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. 12

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. 13

14

15

16

17

18

19

20

21

22