Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

12
Lecture 26

Transcript of Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Page 1: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Lecture 26

Page 2: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Recap Saving PlotsSummary of Chapter 5Introduction of Chapter 6

Page 3: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Function M-filesUser-defined functions are stored as M-files and can be

accessed by MATLAB if they are in the current folder or on MATLAB’s search path

Page 4: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Syntax of Function M-fileBoth built-in MATLAB ® functions and user-defined MATLAB functions have

the same structureEach consists of a name, user-provided input, and calculated output.For example: the function

cos(x) is named cos takes the user input inside the parentheses (in this case, x ) calculates a result

The user does not see the calculations performed, but just accepts the answerUser-defined functions work the same way Imagine that you have created a function called my_function Using

my_function(x)

in a program or from the command window will return a result, as long as x is defined and the logic in the function definition works

Page 5: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Continued…. User-defined functions are created in M-fi les. Each must start with a function-definition

line that contains: The word function A variable that defines the function output A function name A variable used for the input argument

For example:

function output = my_function(x)

is the first line of the user-defined function called my_function It requires one input argument, which the program will call x , and will calculate one

output argument, which the program will call output The function name and the names of the input and output variables are arbitrary and are

selected by the programmer Here’s an example of an appropriate fi rst line for a function called calculation :

function result = calculation(a) In this case, the function name is calculation , the input argument will be called a in any

calculations performed in the function program, and the output will be called result Although any valid MATLAB ® names can be used, it is good programming practice to

use meaningful names for all variables and for function names

Page 6: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Continued….Here’s an example of a very simple MATLAB function that calculates the value

of a particular polynomial: function output = poly(x) %This function calculates the value of a third-order %polynomial output = 3*x.^3 + 5*x.^2 - 2*x +1;

The function name is poly , the input argument is x , and the output variable is named output

Before this function can be used, it must be saved into the current folderThe file name must be the same as the function name in order for MATLAB to

find itAll of the MATLAB naming conventions we learned for naming variables apply

to naming user-defined functions. In particular, The function name must start with a letter. It can consist of letters, numbers, and the underscore. Reserved names cannot be used. Any length is allowed, although long names are not good programming practice.

Page 7: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Continued…. Once the M-file has been saved, the function is available for use from the command window, from a script

M-fi le, or from another function You cannot execute a function M-file directly from the M-file itself. This makes sense, since the input

parameters have not been defined until you call the function from the command window or a script M-file Consider the poly function just created. If, in the command window, we type

poly(4) then MATLAB responds with

ans =265 If we set a equal to 4 and use a as the input argument, we get the same result:

a = 4; poly(a) ans =265

If we define a vector, we get a vector of answers. Thus, y = 1:5; poly(y) gives ans =7 41 121 265 491

If, however, you try to execute the function by selecting the save-and-run icon from the function menu bar, the following error message is displayed:

???Input argument “x” is undefined. Error in ==> poly at 3 output = 3*x.^3 + 5*x.^2 - 2*x +1;

The value of x must be passed to the function when it is used—either in the command window or from within a script M-file program.

Page 8: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Comments As with any computer program, code should be commented

liberally so that it is easy to followHowever, in a MATLAB function, the comments on the line

immediately following the very first line serve a special roleThese lines are returned when the help function is queried from the

command windowConsider, for example, the following function:function results = f(x)%This function converts seconds to minutesresults = x./60;

Querying the help function from the command windowhelp f

returnsThis function converts seconds to minutes

Page 9: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Functions with Multiple Inputs and OutputsJust as the predefined MATLAB functions may require

multiple inputs and may return multiple outputs, more complicated user-defined functions can be written

Recall, for example, the remainder function. This predefined function calculates the remainder in a division problem and requires the user to input the dividend and the divisor

For the problem , the correct syntax isrem(5,3)

which givesans=2

Page 10: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Continued….Similarly, a user-defined function could be written to multiply two vectors together:

function output = g(x,y) % This function multiplies x and y together % x and y must be the same size matrices a = x .*y; output = a;

When x and y are defined in the command window and the function g is called, a vector of output values is returned: x = 1:5; y = 5:9; g(x,y) ans = 5 12 21 32 45

The comment lines can be used to let users know what kind of input is required and to describe the function

In this example, an intermediate calculation ( a ) was performed, but the only output from this function is the variable we’ve named output

This output can be a matrix containing a variety of numbers, but it’s still only one variable

Page 11: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Continued…. Such functions can also be created that return more than one output variable Many of the predefined MATLAB functions return more than one result For example: max returns both the maximum value in a matrix and the element number at which

the maximum occurs. To achieve the same result in a user-defined function, make the output a matrix of answers instead of a single variable, as in

function [dist, vel, accel] = motion(t) % This function calculates the distance, velocity, and % acceleration of a particular car for a given value of t % assuming all 3 parameters are initially 0. accel = 0.5 .*t; vel = t.^2/4; dist = t.^3/12;

Once saved as motion in the current folder, you can use the function to find values of distance , velocity , and acceleration at specified times:

[distance, velocity, acceleration] = motion(10) distance =83.33 velocity =25 acceleration =5

If you call the motion function without specifying all three outputs, only the first output will be returned:

motion(10) ans =83.333

Page 12: Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.

Continued…. Remember, all variables in MATLAB are matrices, so it’s important in the preceding

example to use the .* operator, which specifies element-by-element multiplication For example: using a vector of time values from 0 to 30 in the motion function

time = 0:10:30; [distance, velocity, acceleration] = motion(time) returns three vectors of answers: distance =0 83.33 666.67 2250.00 velocity =0 25.00 100.00 225.00 acceleration =0 5.00 10.00 15.00

It’s easier to see the results if the vectors are grouped together, as in results = [time',distance',velocity',acceleration']

which returns results =

0 0 0 0

10.00 83.33 25.00 5.00

20.00 666.67 100.00 10.00

30.00 2250.00 225.00 15.00 Because time , distance , velocity , and acceleration were row vectors, the transpose

operator was used to convert them into columns