introduction to matlab programming

46
Introductio n To MATLAB Programming Chapter 2

Upload: fawzi

Post on 23-Feb-2016

82 views

Category:

Documents


0 download

DESCRIPTION

Introduction To MATLAB Programming. Chapter 2. MATLAB Programming. Interactive MATLAB use only good if problem is simple Often, many steps are needed We also want to be able to automate repeated tasks Automated data processing is common in Earth science!. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction To MATLAB Programming

Introduction To MATLAB Programming

Chapter 2

Page 2: Introduction To MATLAB Programming

MATLAB Programming• Interactive MATLAB use

• only good if problem is simple

• Often, many steps are needed• We also want to be able to

automate repeated tasks

• Automated data processing is common in Earth science! Automated Earthquake Detection and Notification (USGS)

Automated Stream Discharge Monitoring (USGS)Amazon.com’s Automated Kiva Robots

Page 3: Introduction To MATLAB Programming

Program vs. Script• Computers only understand low-level language machine code

• http://en.wikipedia.org/wiki/Machine_code• Low-level languages are much faster, but very difficult for humans to write

efficiently

• MATLAB is a high-level language• Uses code that is human readable• Much easier to write• E.g. “disp”, “fprintf”, “plot”, etc…

• Compiler: Translates a high level language into an executable object code program (*.exe in MS Windows)

• Creates an executable file (binary) from source code (ascii)E.g. Mozilla Firefox and Microsoft Office (source code: C++) firefox.exe winword.exe (machine language executable files)

• MATLAB does something a little different…

Page 4: Introduction To MATLAB Programming

Program vs. Script• MATLAB is an interpreted language

• Code is read line by line by an interpreter (not a compiler)• Each line of code is translated into machine language and executed on the fly• No .exe file is generated (can force MATLAB to make .exe files)

• Because MATLAB code is not compiled…• source code is referred to as a script• Also called M-files (end in .m)

• Advantages• Don’t need to spend time compiling the code to use it• Don’t need to recompile after you make changes• Same script will work on any operating system with MATLAB

• Disadvantages• Because code is compiled on the fly, some tasks can be slow*• Others can change your code*

Page 5: Introduction To MATLAB Programming

Algorithm Example• Before starting to write any code, you should break the

problem down into a simple algorithm• Algorithm: A sequence of steps to solve a problem• Example Algorithm: Calculate Volume of a Sphere

• Get the input: radius of sphere• Calculate the result: volume of sphere• Display the result

• Input typically comes from:• The user typing in a value when prompted• A file on your hard disk

• Output typically goes to:• The screen (i.e. the MATLAB command window)• A file on your hard disk

Page 6: Introduction To MATLAB Programming

Algorithm ExampleExample Algorithm: Calculate Volume of a Sphere1. Get the input: radius of sphere

• Set the radius• Store the radius in a variable

2. Calculate the result: volume of sphere• Plug radius into volume equation• Store result in variable

3. Display the result• We’ll do this later…

Page 7: Introduction To MATLAB Programming

Simple Script ExampleThe top of all scripts should contain commented documentation• H1 line: a short

comment on what the script does

• “lookfor” will read this

• Subsequent lines• Script name• Author info• Date• Details of what the

code does• Usage (if a function)• Leave one blank line

before starting code• Read by “help” and

“doc”

Page 8: Introduction To MATLAB Programming

Documenting Your Code• Any line of MATLAB code that begins with “%” is ignored by the interpreter

• Referred to as: “comments”• Do not slow down execution of your code• MATLAB doesn’t even read comments, but people do• Comments allow you to tell yourself and others what you did• Typically you can fit most comments into a single line

%set the radius valuerad = 23;%compute the areaArea = pi * (rad ^ 2);%MATLAB ignores commented lines. Use them!!!

In this class:• uncommented code gets a zero• Every line of code must have a brief comment• In all scripts, separate into sections

1) Header/Documentation2) Calculations3) Plotting4) Output

Page 9: Introduction To MATLAB Programming

Input Function• Sometimes we want to ask the user for an input

• More general than hard-coding values into a script• I/O – Input and output(The default input device in MATLAB is the keyboard)

The user’s value is stored in “rad” as a double

Warning! The variable is assumed to be a double

The user can signify a string by using single quotes

Better: Use the ‘s’ option. Input is casted as a string

Page 10: Introduction To MATLAB Programming

Input Function Examples

Because “rad” is stored, you can use it later

Why does this not give the expected result? What happened here?

Why are the single quotes stored?

Page 11: Introduction To MATLAB Programming

Output Statements: disp• To be a useful, a script must be able to output a result• Simplest output: Print to the command window

• Use either “disp” or “fprintf”

“disp” can print strings or numbers

“disp” can print variables

“disp” can only print one thing at a time.For this reason, MATLAB also provides “fprintf”

Page 12: Introduction To MATLAB Programming

Output Statements: fprintf• fprintf has a somewhat confusing syntax

• Most programming languages have fprintf (or printf)• Syntax was inherited from C / C++

“fprintf” does not include a new line (“\n”) after a string, unless you tell it to do so.

Use the new line special character, “\n”You do not need a space before or after a special character, but adding a space makes code easier to read.

“fprintf” also recognizes these special charactersFor more info, see “doc fprintf” and click on the “formatting strings” link near the bottom of the page

Page 13: Introduction To MATLAB Programming

Output Statements: fprintf• “fprintf” can also be used to print variables

• Can apply special formatting to numeric variable (Very Useful!!)

“fprintf” recognizes these conversion charactersFor more info, see “doc fprintf” and click on the “formatting strings” link near the bottom of the page

When you use fprintf to print a variable, a variable is indicated by a place holder, in this case “%d”The variable name must be given after the string.

“%f” indicates that a floating point number is to be printed.

Can print multiple variables in one line! (“disp” can’t do this)

Page 14: Introduction To MATLAB Programming

Output Statements: fprintf• “fprintf” and %f can be used to control just about every

aspect of the formatting of a floating point number

By default, 7 digits are shown, even though MATLAB variables are stored with 17 digits of precision (if needed)

Want to print π rounded to two decimal places?

Want to print a variable in scientific notation with 5 decimal places?

MATLAB double variables can hold only 17 digits. Anything beyond the 17th place gets displayed as a zero and is not stored.

MATLAB uses a compact format by default, so numbers get displayed in scientific notation.“fprintf” can override this!

Page 15: Introduction To MATLAB Programming

Output Statements: fprintf• “fprintf” is also great for printing out numbers so they are

in neat columns.Note the different results. How does this work?%6.2fLeave at least 6 total spaces for each numberincludes decimals, exponents, and negative signsRound to 2 decimal places

%06.2fSame as above, but show leading zeros Note that “fprintf” treats matrices/vectors in strange ways!

Page 16: Introduction To MATLAB Programming

Output Statements: Matrices• “fprintf” treats matrices in strange ways

• Although the behavior is strange, it is consistent• “disp” is much better for printing a matrix to the screen

“disp” does the job, but the output is not formatted

“fprintf” can do the job, but it is awkward, and should only be used as a last resort

Page 17: Introduction To MATLAB Programming

Scripts to Produce Plots• MATLAB has numerous built-in plotting functions

• we can automate visualization of data!

Make two data sets to plot: (x,y) and (x,y2)

Make two data sets to plot: (x,y) and (x,y2)

Why is this plot unacceptable?

Page 18: Introduction To MATLAB Programming

Scripts to Produce Plots• Why not put all of the commands into a script?

• More efficient than typing into the command window

Let’s Make this plot acceptable!

Page 19: Introduction To MATLAB Programming

Scripts to Produce Plots

Added in axis labels (with units)Specifies the plotted range so show the curve better

This plot is labeled and is acceptable

• “plot” is a very powerful function• “doc plot” and read many times!• Also, “doc linespec” is critical

Page 20: Introduction To MATLAB Programming

Scripts to Produce Plots

This plot is a bit overwhelming.

I just do this to demonstrate the capabilities of “plot”

Page 21: Introduction To MATLAB Programming

Scripts to Produce Plots

Page 22: Introduction To MATLAB Programming

Multiple Plots In One Figure: Subplot

Page 23: Introduction To MATLAB Programming

Writing Data To FilesOften read/writing from external files is useful• Three basic file modes

• Read: Just read; do not change• Write: Write from beginning of file to end• Append: Add to the end of an existing file

• MATLAB offers several commands/functions that can write data to files

• “save”• “dlmwrite”• “fprintf”

Page 24: Introduction To MATLAB Programming

Writing Data To Files: “save”• “save” is the simplest way to save data to a file

• Is also most limited• Default is to write a binary .mat file (not usually what you want)

Page 25: Introduction To MATLAB Programming

Writing Data To Files: “save”• By default, save will write ascii files with only 8 digits of

precision.• To override and print all 17 digits, use ‘-double’

Page 26: Introduction To MATLAB Programming

Writing Data To Files: “save”• By using the ‘-append’ option, you can add to files that already

exist• This is a way to print files that do not have a constant number of

columns

Page 27: Introduction To MATLAB Programming

Writing Data To Files: “dlmwrite”• “dlmwrite” is a slightly more flexible version of save

• Can choose the delimiter between values• Can format output (uses fprintf style conversion characters)

“dlmwrite” prints data whatever “format” MATLAB is using

• How can we get the output to look cleaner?

• Specify the ‘precision’• uses fprintf conversion

characters!

Page 28: Introduction To MATLAB Programming

Writing Data To Files: “dlmwrite”• “dlmwrite” can use fprintf style conversion characters

• Use ‘-precision’ option

• What if we want each column to be formatted differently?• “fprintf”!!!• We’ll learn this later

once we know loops

Page 29: Introduction To MATLAB Programming

Reading Data From FilesThe simplest way to read in data from an external file into MATLAB is the “load” command• Files MUST have:

• Consistent numbers of columns• Only numeric data• Can also load .mat files (not usually what you want)

Let’s make two data files with some random

numbers

Page 30: Introduction To MATLAB Programming

Sample Data Files

Page 31: Introduction To MATLAB Programming

Reading Data From Files• “load” stores everything in one matrix

• You can separate things out later if it makes your code clearer• The filename (minus the extension) is the variable name• Or you can set the variable name (this is MUCH better)

Page 32: Introduction To MATLAB Programming

Reading Data From Files• “load” stores everything in one matrix

• You can separate things out later if it makes your code clearer

Page 33: Introduction To MATLAB Programming

Reading Data From Files• “load” stores everything in one matrix

• You can separate things out later if it makes your code clearer

Page 34: Introduction To MATLAB Programming

User-Defined Functions• You have already used many built in functions in MATLAB

• plot, sin, cos, int8, double, fprintf, linspace, etc…

• For example “linspace”The “Call”, or “calling” the function

“Arguments”

Where the “returned” value is stored

Page 35: Introduction To MATLAB Programming

User-Defined Functions• Lets look at the general function setup

• Example: Converting mph to m/s

The “function header” (required for all functions)

The reserved word, “function” (1st line must start with this)

Name of function (identical to name of m-file without .m)

Input arguments (must be provided by the user)

Value that is “returned” (not all functions need to return something)

Page 36: Introduction To MATLAB Programming

User-Defined Functions• Function must be in your

pwd or MATLAB path• Call by function name

• no .m at end• Same as scripts!

• Why ans = 29.0576?

All variables inside a function are local variables• Only exist inside the

function!!• May be confusing at first,

but keeps things tidy• User doesn’t care about

all of the intermediate variables

• Only wants the returned value

Why are “v” and “mph” not defined

in the command window?

Page 37: Introduction To MATLAB Programming

User-Defined Functions

All of these variables are local!

The user won’t be aware of them unless he/she opens the m-file

• Functions can use any number of variables

Page 38: Introduction To MATLAB Programming

A Poorly Written Function• Why is this a bad idea?

• This is NOT how you return a result• The result, v, is not

accessible to the user

Page 39: Introduction To MATLAB Programming

Another Poorly Written Function• Why is this even worse?

Page 40: Introduction To MATLAB Programming

Another Poorly Written Function

• Returned value was stored in “ans”• Not illegal, but bad programming

• Local variables should not be printed to the screen

• Confusing!!• Not accessible to the user• Printing variables is slow

Page 41: Introduction To MATLAB Programming

Functions That Make Plots• Functions can

• Accept more than one argument (separated by commas)• Make plots

Page 42: Introduction To MATLAB Programming

Functions That Make Plots• Functions can

• Accept more than one argument (separated by commas)• Make plots

Page 43: Introduction To MATLAB Programming

Functions That Return Multiple Values• Functions can return multiple values

• Or even matrices!

Page 44: Introduction To MATLAB Programming

Functions That Return Multiple Values• Functions can return

multiple values• Or even matrices!

If you only specify one variable, only the first returned

value is stored

How could we return both “x” and “y” as

one matrix “xy”?

Page 45: Introduction To MATLAB Programming

A Script That Calls A Function

Page 46: Introduction To MATLAB Programming

Thoughts on FunctionsWhy Make Functions?• When a task is often repeated, functions save time• Faster than using “prompt”

When Writing a Function…• Start by sketching out the basic algorithm (pencil & paper)• Write algorithm first as a script

• Difficult to troubleshoot functions because variables are local• Once the script works, generalize it into a function

• Functions do not need to return a value• Some functions make plots, print information, or write files

• If a function does not require an input argument• It should probably be left as a script

• Remember that scripts can call functions multiple times