pptx

advertisement
Chapter 2
• 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!
Amazon.com’s Automated Kiva Robots
Automated Earthquake Detection and Notification (USGS)
Automated Stream Discharge Monitoring (USGS)
• 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…
• 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*
• 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
Example Algorithm: Calculate Volume of a Sphere
1. 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…
The 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”
• 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 value
rad = 23;
%compute the area
Area = 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)
2)
3)
4)
Header/Documentation
Calculations
Plotting
Output
• 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
The user can signify a string by using single quotes
Warning! The variable is assumed to be a double
Better: Use the ‘s’ option. Input is casted as a string
Because “rad” is stored, you can use it later
Why are the single quotes stored?
Why does this not give the expected result?
What happened here?
• 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”
• 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 characters
For more info, see “doc fprintf” and click on the
“formatting strings” link near the bottom of the page
• “fprintf” can also be used to print variables
• Can apply special formatting to numeric variable (Very Useful!!)
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.
“fprintf” recognizes these conversion characters
For more info, see “doc fprintf” and click on the
“formatting strings” link near the bottom of the page
Can print multiple variables in one line! (“disp” can’t do this)
• “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)
MATLAB double variables can hold only 17 digits.
Anything beyond the 17th place gets displayed as a
zero and is not stored.
Want to print π rounded to two decimal places?
Want to print a variable in scientific notation with 5
decimal places?
MATLAB uses a compact format by default, so
numbers get displayed in scientific notation.
“fprintf” can override this!
• “fprintf” is also great for printing out numbers so they are
in neat columns.
Note the different
results. How does this
work?
%6.2f
Leave at least 6 total
spaces for each
number
includes decimals,
exponents, and
negative signs
Round to 2 decimal
places
%06.2f
Same as above, but
show leading zeros
Note that “fprintf” treats matrices/vectors in strange ways!
• “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
• 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?
• Why not put all of the commands into a script?
• More efficient than typing into the command window
Let’s Make this plot acceptable!
• “plot” is a very powerful function
• “doc plot” and read many times!
• Also, “doc linespec” is critical
This plot is labeled and is acceptable
Added in axis labels (with units)
Specifies the plotted range so show the curve better
This plot is a bit
overwhelming.
I just do this to demonstrate
the capabilities of “plot”
Often 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”
• “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)
• By default, save will write ascii files with only 8 digits of
precision.
• To override and print all 17 digits, use ‘-double’
• 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
• “dlmwrite” is a slightly more flexible version of save
• Can choose the delimiter between values
• Can format output (uses fprintf style conversion characters)
• How can we get the
output to look cleaner?
• Specify the ‘precision’
• uses fprintf conversion
characters!
“dlmwrite” prints data whatever “format” MATLAB is using
• “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
The 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
• “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)
• “load” stores everything in one matrix
• You can separate things out later if it makes your code clearer
• “load” stores everything in one matrix
• You can separate things out later if it makes your code clearer
• 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
• 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)
• 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?
• Functions can use
any number of
variables
All of these
variables are local!
The user won’t be
aware of them
unless he/she opens
the m-file
• Why is this a bad idea?
• This is NOT how you return
a result
• The result, v, is not
accessible to the user
• Why is this even worse?
• 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
• Functions can
• Accept more than one argument (separated by commas)
• Make plots
• Functions can
• Accept more than one argument (separated by commas)
• Make plots
• Functions can return multiple values
• Or even matrices!
• 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”?
Why 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
Download