• No results found

M-files (1).pptx

N/A
N/A
Protected

Academic year: 2020

Share "M-files (1).pptx"

Copied!
35
0
0

Loading.... (view fulltext now)

Full text

(1)

M-files

(2)

M-files

Learning objectives:

Learning how to create well-documented M-files in the edit window

and invoke them from the command window.

(3)

We have now used the MATLAB® product interactively in the

Command Window. That is sufficient when all that is needed is a simple calculation.

However, in many cases, many steps are required before the final

(4)

An M-file consists of a series of statements that can be run all at once.

(5)

Script files

A script file is merely a series of MATLAB commands that are saved on

a file. They are useful for retaining a series of commands that you want to execute on more than one occasion.

The script can be executed by typing the file name in the command

(6)

To create a script, click File, then New, then M-file. A new window will

appear called the Editor. To create a new script, simply type the

sequence of statements (notice that line numbers will appear on the left).

When finished, save the file using File and then Save. Make sure that

the extension .m is on the filename (this should be the default). The

(7)

area_circle.m

% This program calculates the area of a circle% First the radius is assigned

radius = 5

% The area is calculated based on the radius

(8)

Comments

The first comment at the beginning of the script describes what the

(9)

The first block of comments (defined as contiguous lines at the

beginning)

will be displayed. For example, for area_circle:>> help area_circle

This program calculates the area of a circle

The reason that a blank line was inserted in the script between the first

(10)

Editing a script file

Once the script has been executed, you may find that you want to

make changes to it (especially if there are errors!). To edit an existing file, there are several methods to open it. The easiest are:

Click File, then Open, then click the name of the file.

Click the Current Directory tab (if it is not already shown), then

(11)

Create a script file for the data

below

• Multiple data sets in one plot

• Multiple (x; y) pairs arguments create multiple graphs with a single call to plot. For example, these statements plot three related functions of x: y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 cos(x), in the interval 0 ≤ x ≤ 2π.

• >> x = 0:pi/100:2*pi;

>> y1 = 2*cos(x); • >> y2 = cos(x);

>> y3 = 0.5*cos(x);

• >> plot(x,y1,'--',x,y2,'-',x,y3,':')

• >> xlabel('0 \leq x \leq 2\pi')

• >> ylabel('Cosine functions')

• >> legend('2*cos(x)','cos(x)','0.5*cos(x)')

• >> title('Typical example of multiple plots')

(12)

Scripts with input and output

Let us create a script file called area_circle.m and use input and

(13)

• area_circle.m

• % This script calculates the area of a circle • % It prompts the user for the radius

• % and calculates the area based on that radius • radius = input(‘Please enter the radius: ’);

area = pi * (radius^2);

• % Print all variables in a sentence format

• fprintf(‘For a circle with a radius of %.2f,’,radius) • fprintf(‘the area is %.2f\n’,area)

• Executing the script produces the following output: • >> area_circle

• Please enter the radius: 3.9

(14)

Exercises

1. Write a script that will prompt the user for an angle in degrees. It will then calculate the angle in radians, and then print the result. Note: π radians = 180°.

2. Write a simple script that will calculate the volume of a hollow sphere that is ,

(

r0³- ri³

)

where riis the inner radius and r0 is the outer radius. Use the input function to prompt the user to enter both the inner and outer radii of the hollow sphere and then subsequently calculate the volume. Include comments in the script.

(15)

Exercises

4. If the lengths of two sides of a triangle and the angle between them are known, the length of the third side can be calculated. Given the lengths of two sides (b and c) of a triangle, and the angle between them α in degrees, the third side a is calculated as:

a2 = b2 + c2 -2bc cos(α)

Write a script thirdside that will prompt the user and read in values for b, c, and α (in degrees), and

then calculate and print the value of a with three decimal places.

• (Note: To convert an angle from degrees to radians, multiply the angle by π /180.)

The format of the output from the script should look exactly like this:>> thirdside

Enter the first side: 2.2 • Enter the second side: 4.4

(16)

Function files

Function files are M-files that start with the word function. In contrast

(17)

The syntax for the function file can be represented generally as

function outvar = funcname(arglist)% helpcomments

statements

(18)

where outvar = the name of the output variable, funcname = the

function’s name, arglist = the function’s argument list (i.e., comma-delimited values that are passed into the function), helpcomments = text that provides the user with information regarding the function.

The M-file should be saved as funcname.m so that there will be no

(19)

Input and output arguments

Examples:

function C=FtoC(F) One input argument and one output argumentfunction area=TrapArea(a,b,h) Three inputs and one output

(20)

For example, the following is a function called calcarea, which

calculates and returns the area of a circle; it is stored in a file called calcarea.m.

calcarea.m

function area = calcarea(rad)

(21)

Calling a function

• Here is an example of a call to this function in which the value returned is stored in the default variable

ans:

>> calcarea(4)

• ans =

• 50.2655

• The result returned from this function can also be stored in a variable in an assignment statement such as;

• >> area = calcarea(5)

• area =

• 78.5398

• >> myarea = calcarea(6)

myarea =

(22)

Calling a User-Defined Function

from a Script

Now, we’ll modify our script that prompts the user for the radius and calculates the area of a circle, to call our function calcarea to calculate the area of the circle rather than doing this in the script.

• script3.m

% This script calculates the area of a circle% It prompts the user for the radius

• radius = input(‘Please enter the radius: ’);

• % It then calls our function to calculate the

• % area and then prints the result

• area = calcarea(radius);

• fprintf(‘For a circle with a radius of %.2f,’,radius)

(23)

Passing Multiple Arguments

In many cases it is necessary to pass more than one argument to a function.

For example, the volume of a cone is given by V = πr²h

where r is the radius of the circular base and h is the height of the cone.

Therefore, a function that calculates the volume of a cone needs both the radius and the height:

conevol.m

function outarg = conevol(radius, height)% Calculates the volume of a cone

(24)

Since the function has two input arguments in the function header,

two values must be passed to the function when it is called. The order makes a difference. The first value that is passed to the function is

stored in the first input argument (in this case, radius), and the

second argument in the function call is passed to the second input argument in the function header.

This is very important:

The arguments in the function call must correspond one-to-one with

(25)

Here is an example of calling this function. The result returned from the

function is simply stored in the default variable ans.

>> conevol (4,6.1)ans =

102.2065

In the next example, the result is printed instead with a format of two decimal

places.

>> fprintf(‘The cone volume is %.2f\n’,...conevol(3, 5.5))

(26)

disp and fprintf

Output Statements: disp and fprintf

• Output statements display strings and the results of expressions, and can allow for formatting, or customizing how they are displayed. The simplest output function in MATLAB is disp, which is used to display the result of an expression or a string without assigning any value to the

default variable ans. However, disp does not allow formatting. For example,

>> disp(‘Hello’)

• Hello

>> disp(4^3)

• 64

• Formatted output can be printed to the screen using the fprintf function. For example,

>> fprintf(‘The value is %d, for sure!\n’,4^3)

(27)

To the fprintf function, first a string (called the format string) is

passed, which contains any text to be printed as well as formatting

information for the expressions to be printed. In this example, the %d is an example of format information.

The %d is sometimes called a placeholder; it specifies where the value

(28)

Exercises

1. Write a function file that converts temperature in degrees Fahrenheit (F) to degrees Centigrade (C). Use input and fprintf commands to display a mix of text and numbers. Recall the conversion formulation, C = 5/9 * (F - 32).

2. Write a user-defined MATLAB function, with two input and two output arguments that determines the height in centimeters (cm) and mass in

kilograms (kg)of a person from his height in inches (in.) and weight in pounds (lb).

(a) Determine in SI units the height and mass of a 5 ft.11 in. person who

weighs 180 lb.

(29)

Exercises

3. Write a script that will prompt the user for the radius and height, call the function conevol to calculate the cone volume, and print the result in a nice sentence format. So, the program will consist of a script and the conevol function that it calls.

4. The velocity of an aircraft typically is given in either miles/hour or meters/second. Write a function that will receive one input argument that is the velocity of an airplane in miles per

hour and will return the velocity in meters per second. The relevant conversion factors are: one hour = 3600 seconds, one mile = 5280 feet, and one foot = .3048 meters.

5. If a certain amount of money (called the principal P) is invested in a bank account, earning an interest rate i compounded annually, the total amount of money Tn that will be in the

account after n years is given by:

Tn = P(1+i)n

(30)

Exercises

6. The Body Mass Index, or BMI, for a person is defined, using US units, as

BMI = 703*

where the weight is in pounds and the height is in total inches. Write a function called findbmi

that would receive the weight and height as input arguments, and would return the BMI. For example, to find the BMI for a person who weighs 170 pounds and is 5’ 11’’ tall (so 71 inches tall), here are two examples of function calls:

>> findbmi(170,71)ans =

23.7076

>> bmi = findbmi(170,71)bmi =

(31)

Exercises

7. Write a function degf_to_k that will convert a temperature from degrees Fahrenheit (F) to Kelvin (K). It will receive one input argument that is degrees Fahrenheit, and it will return the temperature in K. Here are conversions from F to Celsius and from C to K:

• C = (F – 32) * 5/9

• K = C + 273.15

• Here are examples of calling this function:

>> ktemp = degf_to_k(33.3)

• ktemp =

• 273.8722

>> fprintf(‘%.2f degrees F is %.2f degrees K\n’, −15.3, ...

• degf_to_k(−15.3))

(32)

8. An approximation for a factorial can be found using Stirling’s formula: n! = n

(33)

Functions that Accomplish a

Task Without

Returning Values

Many functions do not calculate values, but rather accomplish a task such as

printing formatted output. Since these functions do not return any values, there are no output arguments in the function header.

The general form of a function definition for a function that does not return

any values looks like this:

%functionname.m

function functionname(input arguments)

% Comment describing the function

Statements here

Notice what is missing in the function header: there are no output

(34)

For example, the following function just prints the number of arguments passed

to it in a sentence format:

%printem.m

function printem(a,b)

% This function prints two numbers in a sentence format

fprintf(‘The first number is %.1f and the second is %.1f\n’,a,b)

Since this function isn’t calculating anything, there aren’t any output arguments

in the function header, and no =. An example of a call to the function is:

>> printem(3.3, 2)

(35)

Note that since the function isn’t returning any value, it cannot be

called from an assignment statement. Any attempt to do this would result in an error, for example,

>> x = printem(3, 5) % Error!! ??? Error using ==> printem Too many output arguments.

• We can therefore think of the call to a function that does not return values as a statement by itself, in that the function call cannot be

References

Related documents

Online community: A group of people using social media tools and sites on the Internet OpenID: Is a single sign-on system that allows Internet users to log on to many different.

Differences among nonmedical prescription stimulant users and student characteristics (race, gender, academic performance (GPA), living arrangement, alcohol and other drug usage,

Given that Ministers already have to satisfy themselves that the land is eligible land, (i.e. abandoned or neglected), and that purchase by the community body is

For the poorest farmers in eastern India, then, the benefits of groundwater irrigation have come through three routes: in large part, through purchased pump irrigation and, in a

Taffs and Holt (2013, p.501) state that “in order to be accessed, resources must match student needs as well as their expectations”, and a primary goal in the development of

1. Awarding institution  The Royal Veterinary College and the London  School of Hygiene and Tropical Medicine 

AASR achieved for a three-channel system, using back-projection and the beamforming approach for the correction of the topographic contribution for a perpendicular baseline of ±89 m

i) Benefits of technology would be passed onto customers. All domestic voice calls for Jio customers will be absolutely free, across India and at any time. Domestic