1 / 36

Lecture 2

Lecture 2. What will I learn in this lecture?. What is a Matlab function? How does the plot function work? What Matlab functions are available to do Data Analysis? How can you create your own function ? Readings: Matlab by Pratap Chapters 2.4, 4.1, 4.2, 4.3, 5.2.2, 5.6.1 .

caia
Download Presentation

Lecture 2

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. Lecture 2

  2. What will I learn in this lecture? What is a Matlab function? How does the plot function work? What Matlab functions are available to do Data Analysis? How can you create your own function ? Readings: Matlab by Pratap Chapters 2.4, 4.1, 4.2, 4.3, 5.2.2, 5.6.1

  3. Matlab Built-in Functions Exponential Function >>exp(0)(exponential function ex ) ans = 1 name argument parenthesis >>x = [-1 0 1]; >> exp(x) ans = 0.3679 1.0000 2.7183( [exp(-1), exp(0), exp(1)] ) The exp function argument can be a scalar, vector or matrix. Basic Mathematical Functions (see 3.2.4 in Pratap) However, since there are hundreds of Matlab functions, a useful tool is Matlab Helpdesk.

  4. Functions Three forms of the use of a function in Matlab are: >> VAR = function_name(arg1,arg2, …);>> [VAR1,VAR2,...] = function_name(arg1,arg2, …); >> function_name(arg1,arg2, …); A Matlab function like a mathematical function is a rule where given a certain input or inputs, the rule tells you how to compute the output value or how to produce an effect (e.g. the plot function produces a figure). The inputs are called the “arguments” to the function.

  5. Functions As an illustration, a function can be likened to the sequence of instructions on an income tax form(see next two slides). • The instructions must be followed in sequential order. • Fields (or boxes in the form represent variables). All variables in a function are local to that function. They cannot been seen by other users filling out other forms. • Fields in the form that must be filled in with information provided by the person whose tax is being computed are called parameters . The values entered in these fields, (like name , social security number),... are called input arguments. • If the taxpayer recieves a return this amount is always found in one specific field on the form, field 67a. This field is called an output variable.

  6. name field

  7. refund amount amount due

  8. 2-D Plotting Example: Plot the sine function using the built-in function “sin” .(see section 5.1) >>x = -10 : .1 : 10;% (remember ; suppresses output) >>y = sin(x);% x in radians >>plot(x,y); By default Matlab will connect the points (xi ,yi) with a straight line. A more general version of the plot command is: plot(x,y,’color_linestyle_marker’); where color is: cyan magenta yellow red green blue white black c m y r g b w k

  9. plot - Function Arguments Linestyle can be any of the following: solid dashed dotted dashed-dot no line line line line line - - - : -. none and marker can be specified as: plus asterisk point cross square diamond + * . x square diamond

  10. Example: >>x = -10 : .1 : 10; >>y = sin(x); >>plot(x,y,’m--square’); Figure Window

  11. Functions Name of functionArguments >>plot(x,y); plot x and y >>plot(x,y,’m--square’);plot x , y and a string >>y = sin(x+1); sin expression “x+1” Note: the function plot can have a variable number of arguments. However, the order of placement of the arguments is significant. On an income tax form, if in field 7 wages, tips,... you typed in the number of dependents you would not expect to compute the true income tax. Example: >>plot(y,x);(may not give the same results as plot(x,y) ) >>plot(’m--square’,x,y);(does not work)

  12. "Calling" a function >>x = pi / 4; % line 1 >>y = sin(x) ; % line 2 During execution of the above lines, the mechanism for the call works this way:1) A copy of the value of the variable x is passed (by Matlab) to the code for the built-in function sin .2) The execution temporarily suspends (at line 2) while the code for the function sin executes. 3) After the code in sin finishes executing, execution proceeds with line 2. The value (.7071…) that the sin function computes is returned to line 2 and replaces the expression shaded in yellow above.

  13. Functions - Expandability Matlab’s built-in functions accept a wide variety of array sizes. Example: The built-in function sum. >>vec1 = [-2 ; 3 ; 4] ;>>vec2 = [-2 3 4] ; >>sum(vec1) input is a 3 x 1 column vector and output is a scalar.ans = 5 >>sum(vec2) input is a 1 x 3 row vector and output is a scalar. ans = 5 (see section 5.3)

  14. Functions - User Defined Users can add to Matlab’s built-in functions by “programming” a function. A program in Matlab is either in the form of a script or a function.Programming a function is described in the Matlab book in Chapter 4.2 and scripts are described in Chapter 4.1.

  15. What is a computer program? Programming - • A process for obtaining a computer solution to a problem. • A computer program is a sequence of instructions that tell the computer what to do.

  16. Why define your own Functions? • Modular Programming Break complicated tasks up into pieces(functions). • Functions can “call” other functions. This means you don’t have to re-write the code for the function again and again. • Variables in Functions are “local”. All variables in the function are “ local ” by default. That means that if you have a variable in your workspace with the same name as the variable in a function, then assigning a value to the variable in the function has no affect on the variable in the workspace. That is, a function cannot accidentally change (destroy) the data in your workspace.

  17. Programming Steps 1. Problem Definition 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) 3. Develop Algorithm (processing steps to solve problem) 4. Write the "Program" (Code) (instruction sequence to be carried out by the computer) 5. Test and Debug the Code 6. Run Code

  18. Functions - An Example 1. Problem Definition Write a function that converts a temperature in Fahrenheit to Celsius. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.)Use the fact that celsius = (fahr - 32) * 5/9

  19. Function Example 3. Develop Algorithm (processing steps to solve problem) Natural-Language Algorithm The function “definition” should list one input variable named fahr and one output variable celsius. Compute the value of the celsius temperature and assign the value to a variable “celsius” The “function” mechanism of Matlab will automatically return the value in the variable celsius when the function is used (called) at the Matlab prompt.

  20. Function Example 4. Write the “Function" (Code)(instruction sequence to be carried out by the computer) Any sequence of Matlab commands can be put in a file. The file suffix should end with a “.m”. The sequence of commands will be executed (from the top of the file down, command by command). >>edit to open the Matlab editor and create a new file. Then type (and save) the following: function celsius = F_to_C(fahr)% This function converts Fahrenheit to Celsius. celsius = (fahr -32)*5/9; Click “File” and then “Save As” to name the file “F_to_C.m”.

  21. Execute(call) the function in by typing “ F_to_C( temperature )”.

  22. Program Example 5. Test and Debug the Code If the program works correctly then it has no “bugs” so bring the Matlab editor back up and close out the Matlab program. Does the program work with only scalar input or does it work with vector values? (see next slide) 6. Run Code Since two points determine a linear function we know the function F_to_C works correctly.

  23. Input is a vector [32 212]

  24. Documentation • prepared during development of a program, as comments within the program and possible additional documentation; e.g., manuals, etc. • Use the “%” symbol to write a comment in a program. • You must put comments in your program describing the function interface - i.e. input and output format. • Also a general description of what the function does. Finally the programmer should identify himself / herself.

  25. Documentation Improved documentation for the F_to_C function. function celsius = F_to_C(fahr) % function celsius = F_to_C(fahr) % This function converts Fahrenheit to Celsius. % input fahr can be a scalar or vector of temps in degree F % output celsius is a scalar or vector of temps in degree C % Programmer: Tom Gambill % Date: 1/30/01 celsius = (fahr -32)*5/9;

  26. Functions - Another Example 1. Problem Definition Write a function that computes the time for a falling object to hit the ground. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Use the fact that height_t = height_0 + velocity_0* time + 1/2 * g * time* time, where height_t is the height of the object at any given time (in seconds), g is the acceleration due to gravity, -9.8 m/s2. velocity_0 is the velocity at time = 0.Therefore to compute the time to impact, set height_t = 0 and solve for time. This equation (after doing some algebra)can be written as:0 = -4.9 * time2 + velocity_0 * time + height_0 This is a quadratic formula in terms of the variable time.

  27. Function Example 2. (continued) The input arguments to the function consists of scalar values for height_0 and velocity_0 and the output is the exact time (in seconds) of contact with the ground. Assumptions: No air resistance and time = 0 when object begins decent. (Also height_0 > 0 implicit) 3. Develop Algorithm (processing steps to solve problem) Natural-Language Algorithm Initial values of height_0 and velocity_0 are provided via the arguments when the function is called. Solve quadratic formula for time Quadratic formula has two solutions, select the positive value as the result to be returned.

  28. Function Example 4. Write the “Function" (Code) (instruction sequence to be carried out by the computer) Use the Matlab editor to create a file “time_to_impact.m” . function time = time_to_impact(height_0,velocity_0) % function time = time_to_impact(height_0,velocity_0) % Input: Two scalars height_0 (meters) and velocity_0 (meters/sec)% Output: time to impact (sec) given initial height is% height_0 and initial velocity is velocity_0.% Programmer: Tom Gambill% Date: 9/10//00% Assumptions: No air resistance% time = zero when object begins decent% g = 9.8 is constantp = [-4.9 , velocity_0, height_0];time=roots(p);time = max(time);

  29. Function Example 5. Test and Debug the Code Although the value of the function is assigned to the variable time, when you execute the function you can assign the value of the function to any variable.(see next slide) 6. Run Code Note: The prefix of the Unix filename must be the same as the name of the function. e.g. if the function name is “time_to_impact” then the filename in Unix must be “time_to_impact.m”. Also, don’t use the same name for a function and a variable in your workspace. (see the next slide for ways to “run” or execute the function)

  30. (Simple) Function - Structure functionoutput_variable= function_name(input_variables) %The line above is called the function definition line. %Simple functions have only one output variable.. %A line that begins with a “%” symbol is called a comment. %Comments are ignored by Matlab but necessary for humans. Body of the function Note: One statement in the body of the function should be of the form,output_variable = expression;

  31. Function Example time_to_impact uses the built-in functions, roots, and max.The function roots (see 5.6.1) computes all the roots of a polynomial. In Matlab polynomials are represented by vectors. e.g. the polynomial, x2 - 1 is represented by >> p = [1 0 -1]; % p is just a vectorTo compute all the roots (x-values where p(x) = 0) of this polynomial type, >> roots(p)ans = -1 1

  32. Function Example From the previous slide, -6+x+x2 is represented by >> p = [1 1 -6]; % p is just a vectorTo evaluate the polynomial p at x = 3 , x = 4 and x = 5(that is to compute p(3), p(4), p(5) use the built-in Matlab function polyval (see 5.2.2), >> polyval(p , [3, 4, 5])ans = 6 14 24

  33. Functions - max , min The functionsmaxormincompute the maximum or minimum value of an array. These functions work on arrays and vectors in a similar manner to the functionsum(slide 2-13). Example >>vec1 = [-2 ; 3 ; 4] ;>>vec2 = [-2 3 4] ; Continued on next slide ...

  34. Functions - max , min >>min(vec2) ans = -2 >>min(vec1) ans = -2 >> max(vec2) ans = 4 >> max(vec1) ans = 4

  35. What have I learned in this lecture? A Matlab function is a sequence of Matlab statements that are entered in a file. The first line of the function called the function definition line and has a specific format. A function is executed whenever it occurs in a Matlab expression that is executing in the Matlab environment.Matlab function filenames end with the .m extension and the filename must be the same as the function name. You create your own function by following a six step design procedure. Functions provide modular design.

More Related