2 Amazon.com’s Automated Kiva Robots MATLAB ProgrammingInteractive MATLAB useonly good if problem is simpleOften, many steps are neededWe also want to be able to automate repeated tasksAutomated data processing is common in Earth science!Automated Earthquake Detection and Notification (USGS)Amazon.com’s Automated Kiva RobotsAutomated Stream Discharge Monitoring (USGS)
3 Program vs. ScriptComputers only understand low-level language machine codeLow-level languages are much faster, but very difficult for humans to write efficientlyMATLAB is a high-level languageUses code that is human readableMuch easier to writeE.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 flyNo .exe file is generated (can force MATLAB to make .exe files)Because MATLAB code is not compiled…source code is referred to as a scriptAlso called M-files (end in .m)AdvantagesDon’t need to spend time compiling the code to use itDon’t need to recompile after you make changesSame script will work on any operating system with MATLABDisadvantagesBecause code is compiled on the fly, some tasks can be slow*Others can change your code*
5 Algorithm ExampleBefore starting to write any code, you should break the problem down into a simple algorithmAlgorithm: A sequence of steps to solve a problemExample Algorithm: Calculate Volume of a SphereGet the input: radius of sphereCalculate the result: volume of sphereDisplay the resultInput typically comes from:The user typing in a value when promptedA file on your hard diskOutput typically goes to:The screen (i.e. the MATLAB command window)
6 Algorithm Example Example Algorithm: Calculate Volume of a Sphere Get the input: radius of sphereSet the radiusStore the radius in a variableCalculate the result: volume of spherePlug radius into volume equationStore result in variableDisplay the resultWe’ll do this later…
7 Simple Script Example Subsequent lines The top of all scripts should contain commented documentationH1 line: a short comment on what the script does“lookfor” will read thisSubsequent linesScript nameAuthor infoDateDetails of what the code doesUsage (if a function)Leave one blank line before starting codeRead by “help” and “doc”
8 Documenting Your CodeAny line of MATLAB code that begins with “%” is ignored by the interpreterReferred to as: “comments”Do not slow down execution of your codeMATLAB doesn’t even read comments, but people doComments allow you to tell yourself and others what you didTypically 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 zeroEvery line of code must have a brief commentIn all scripts, separate into sections1) Header/Documentation2) Calculations3) Plotting4) Output
9 Input Function Sometimes we want to ask the user for an input More general than hard-coding values into a scriptI/O – Input and output(The default input device in MATLAB is the keyboard)The user’s value is stored in “rad” as a doubleThe user can signify a string by using single quotesWarning! The variable is assumed to be a doubleBetter: Use the ‘s’ option. Input is casted as a string
10 Input Function Examples Because “rad” is stored, you can use it laterWhy are the single quotes stored?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 resultSimplest output: Print to the command windowUse 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 syntaxMost 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
13 Output Statements: fprintf “fprintf” can also be used to print variablesCan 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 charactersFor more info, see “doc fprintf” and click on the “formatting strings” link near the bottom of the pageCan 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 numberBy 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.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 zerosNote that “fprintf” treats matrices/vectors in strange ways!
16 Output Statements: Matrices “fprintf” treats matrices in strange waysAlthough 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 functionswe 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 windowLet’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 criticalThis plot is labeled and is acceptableAdded 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”
23 Writing Data To Files Often read/writing from external files is useful Three basic file modesRead: Just read; do not changeWrite: Write from beginning of file to endAppend: Add to the end of an existing fileMATLAB 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 fileIs also most limitedDefault 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 existThis 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 saveCan choose the delimiter between valuesCan 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 charactersUse ‘-precision’ optionWhat 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” commandFiles MUST have:Consistent numbers of columnsOnly numeric dataCan also load .mat files (not usually what you want)Let’s make two data files with some random numbers
31 Reading Data From Files “load” stores everything in one matrixYou can separate things out later if it makes your code clearerThe filename (minus the extension) is the variable nameOr you can set the variable name (this is MUCH better)
32 Reading Data From Files “load” stores everything in one matrixYou can separate things out later if it makes your code clearer
33 Reading Data From Files “load” stores everything in one matrixYou can separate things out later if it makes your code clearer
34 User-Defined Functions You have already used many built in functions in MATLABplot, 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 setupExample: Converting mph to m/sThe “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 pathCall by function nameno .m at endSame as scripts!Why ans = ?All variables inside a function are local variablesOnly exist inside the function!!May be confusing at first, but keeps things tidyUser doesn’t care about all of the intermediate variablesOnly wants the returned valueWhy are “v” and “mph” not defined in the command window?
37 User-Defined Functions Functions can use any number of variablesAll 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 resultThe 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 programmingLocal variables should not be printed to the screenConfusing!!Not accessible to the userPrinting variables is slow
41 Functions That Make Plots Functions canAccept more than one argument (separated by commas)Make plots
42 Functions That Make Plots Functions canAccept more than one argument (separated by commas)Make plots
43 Functions That Return Multiple Values Functions can return multiple valuesOr even matrices!
44 Functions That Return Multiple Values Functions can return multiple valuesOr even matrices!If you only specify one variable, only the first returned value is storedHow could we return both “x” and “y” as one matrix “xy”?
46 Thoughts on Functions Why Make Functions? When a task is often repeated, functions save timeFaster than using “prompt”When Writing a Function…Start by sketching out the basic algorithm (pencil & paper)Write algorithm first as a scriptDifficult to troubleshoot functions because variables are localOnce the script works, generalize it into a functionFunctions do not need to return a valueSome functions make plots, print information, or write filesIf a function does not require an input argumentIt should probably be left as a scriptRemember that scripts can call functions multiple times