Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1

2 2-2 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 2-3 Basic Mathematical Functions (see 3.2.4 in Pratap) However, since there are hundreds of Matlab functions, a useful tool is Matlab Helpdesk. Exponential Function >> exp(0) (exponential function e x ) ans = 1 name argument parenthesis >> x = [-1 0 1]; >> exp(x) ans = 0.36791.00002.7183( [exp(-1), exp(0), exp(1)] ) The exp function argument can be a scalar, vector or matrix.

4 4 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 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-8 Example: Plot the sine function using the built-in function “sin”. (s ee 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 (x i,y i ) 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 2-9 Linestyle can be any of the following: soliddashed dotted dashed-dotno line lineline -- -:-.none and marker can be specified as: plusasteriskpointcross square diamond +*.x square diamond

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

11 2-11 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) >> 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” Name of functionArguments

12 2-12 >> 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 2-13 >> 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 Matlab’s built-in functions accept a wide variety of array sizes. Example: The built-in function sum. (see section 5.3)

14 2-14 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 2-15 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 2-16 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 2-17 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 2-18 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 2-19 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. 3. Develop Algorithm (processing steps to solve problem)

20 2-20 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 2-22 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 2-24 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 2-25 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 2-26 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/s 2. 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 * time 2 + velocity_0 * time + height_0 This is a quadratic formula in terms of the variable time.

27 2-27 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. 3. Develop Algorithm (processing steps to solve problem) 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)

28 2-28 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 constant p = [-4.9, velocity_0, height_0]; time=roots(p); time = max(time);

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

31 2-31 Body of the function Note: One statement in the body of the function should be of the form, output_variable = expression; function output_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.

32 2-32 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, x 2 - 1 is represented by >> p = [1 0 -1]; % p is just a vector To compute all the roots (x-values where p(x) = 0) of this polynomial type, >> roots(p) ans = -1 1

33 2-33 From the previous slide, -6+x+x 2 is represented by >> p = [1 1 -6]; % p is just a vector To 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

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

35 2-35 >> min(vec2) ans= -2 >> min(vec1) ans= -2 >> max(vec2) ans= 4 >> max(vec1) ans= 4

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


Download ppt "2-2 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."

Similar presentations


Ads by Google