1 / 46

Introduction To MATLAB Programming

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

fawzi
Télécharger la présentation

Introduction To MATLAB Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction To MATLAB Programming Chapter 2

  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! Automated Earthquake Detection and Notification (USGS) Amazon.com’s Automated Kiva Robots Automated Stream Discharge Monitoring (USGS)

  3. 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…

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

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

  6. Algorithm Example Example Algorithm: Calculate Volume of a Sphere • Get the input: radius of sphere • Set the radius • Store the radius in a variable • Calculate the result: volume of sphere • Plug radius into volume equation • Store result in variable • Display the result • We’ll do this later…

  7. Simple Script Example 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”

  8. 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 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) Header/Documentation 2) Calculations 3) Plotting 4) Output

  9. 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 can signify a string by using single quotes The user’s value is stored in “rad” as a double Warning! The variable is assumed to be a double Better: Use the ‘s’ option. Input is casted as a string

  10. Input Function Examples Why are the single quotes stored? Because “rad” is stored, you can use it later Why does this not give the expected result? What happened here?

  11. 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”

  12. 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 characters For more info, see “doc fprintf” and click on the “formatting strings” link near the bottom of the page

  13. Output Statements: fprintf • “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)

  14. 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) 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? MATLAB uses a compact format by default, so numbers get displayed in scientific notation. “fprintf” can override this! Want to print a variable in scientific notation with 5 decimal places?

  15. 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.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!

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

  17. 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?

  18. 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!

  19. Scripts to Produce Plots • “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

  20. Scripts to Produce Plots This plot is a bit overwhelming. I just do this to demonstrate the capabilities of “plot”

  21. Scripts to Produce Plots

  22. Multiple Plots In One Figure: Subplot

  23. Writing Data To Files 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”

  24. 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)

  25. 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’

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

  27. 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) • How can we get the output to look cleaner? • Specify the ‘precision’ • uses fprintf conversion characters! “dlmwrite” prints data whatever “format” MATLAB is using

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

  29. Reading Data From Files 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

  30. Sample Data Files

  31. 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)

  32. Reading Data From Files • “load” stores everything in one matrix • You can separate things out later if it makes your code clearer

  33. Reading Data From Files • “load” stores everything in one matrix • You can separate things out later if it makes your code clearer

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

  35. 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)

  36. 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?

  37. User-Defined Functions • 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

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

  39. Another Poorly Written Function • Why is this even worse?

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

  41. Functions That Make Plots • Functions can • Accept more than one argument (separated by commas) • Make plots

  42. Functions That Make Plots • Functions can • Accept more than one argument (separated by commas) • Make plots

  43. Functions That Return Multiple Values • Functions can return multiple values • Or even matrices!

  44. 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”?

  45. A Script That Calls A Function

  46. Thoughts on Functions 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

More Related