Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 2

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

3 Computers only understand low-level language 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 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 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 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…

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

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

11 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 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 “fprintf” can also be used to print variables Can apply special formatting to numeric variable (Very Useful!!) “fprintf” recognizes these conversion characters For 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)

14 “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 17 th 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!

15 “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 “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 MATLAB has numerous built-in plotting functions we can automate visualization of data! Make two data sets to plot: (x,y) and (x,y2) Why is this plot unacceptable?

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

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

21

22

23 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 “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 By default, save will write ascii files with only 8 digits of precision. To override and print all 17 digits, use ‘-double’

26 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 “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!

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

31 “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 “load” stores everything in one matrix You can separate things out later if it makes your code clearer

33 “load” stores everything in one matrix You can separate things out later if it makes your code clearer

34 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 Lets look at the general function setup Example: Converting mph to m/s The “function header” (required for all functions) The reserved word, “function” (1 st 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 Function must be in your pwd or MATLAB path Call by function name no.m at end Same as scripts! Why ans = ? 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 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

38 Why is this a bad idea? This is NOT how you return a result The result, v, is not accessible to the user

39 Why is this even worse?

40 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 can Accept more than one argument (separated by commas) Make plots

42 Functions can Accept more than one argument (separated by commas) Make plots

43 Functions can return multiple values Or even matrices!

44 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

46 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 ppt "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."

Similar presentations


Ads by Google