Function m-Files in MATLAB: Characteristics, Workspaces, and Search Path, Study notes of Engineering

The concept of function m-files in matlab, their characteristics, how they create workspaces, and the rules matlab follows when encountering names in the search path. Function m-files are used to process specific information and generate output based on inputs. They have local input and output variables and can call other functions or script files. Each function creates its own workspace for storing variables created inside it, which can have the same name as variables in the matlab workspace.

Typology: Study notes

Pre 2010

Uploaded on 11/08/2009

koofers-user-tqi
koofers-user-tqi šŸ‡ŗšŸ‡ø

10 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Chapter 14 Function M-files
14.1 M-File Construction Rules
There is another type of m-File besides a MATLAB script file. It is a MATLAB
function m-File. Typically, a MATLAB function file contains a sequence of MATLAB
commands which process specific information passed to it in the form of input variables
and generate output based on the information. A function m-File behaves like a black
box from the user's standpoint because all that is evident are the variables passed to it
from the MATLAB Workspace and those which are returned from it to the Workspace.
Intermediate variables created in the function m-File are not stored in the MATLAB
Workspace and hence will not overwrite any variables of the same name which happen to
be present in the Workspace.
Function m-Files are created with the MATLAB Editor/Debugger and saved as
text files with a .m extension similar to script files. All MATLAB built-in mathematical
functions are function m-Files.
A simple function m-File called floan.m is shown in Example 14.1.1. Its main
purpose is to calculate a mathematical function value based on values passed to it from a
script file called Loan_Interest.m and return the computed value to the calling
program. The calling script file Loan_Interest.m is included as well in order to see
where the function calls occur.
Example 14.1.1
function i_R = floan(AA,PP,NN,ii)
% floan is a function called by the script file 'Loan_Interest.m'
% It accepts a monthly payment AA, loan amount PP, a loan duration NN
% (in years) and an interest rate ii. It returns a single value
% determined from evaluation of the function. The script file
% 'Loan_Interest.m' is a root solving program which attempts to find
% the root iR of f(A,P,N,i)=0. The user selects from one of two root
% solvers, the Bisection Method or the Method of False Position. The
% root iR found in 'Loan_Interest.m' is the annualized interest (in
% percent).
N_months=12*NN; % Convert from years to months
if ii~=0 % Check if ii not equal 0
x=1+ii;
i_R=AA/PP-(ii*x^N_months)/(x^N_months-1); % Calculate function
% value when ii not equal 0
else % ii equals 0
i_R=AA/PP - 1/N_months % Calculate function value when ii equals 0
end % if ii~=0 % Check if ii not equal 0
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Function m-Files in MATLAB: Characteristics, Workspaces, and Search Path and more Study notes Engineering in PDF only on Docsity!

Chapter 14 Function M-files

14.1 M-File Construction Rules

There is another type of m-File besides a MATLAB script file. It is a MATLAB

function m-File. Typically, a MATLAB function file contains a sequence of MATLAB

commands which process specific information passed to it in the form of input variables

and generate output based on the information. A function m-File behaves like a black

box from the user's standpoint because all that is evident are the variables passed to it

from the MATLAB Workspace and those which are returned from it to the Workspace.

Intermediate variables created in the function m-File are not stored in the MATLAB

Workspace and hence will not overwrite any variables of the same name which happen to

be present in the Workspace.

Function m-Files are created with the MATLAB Editor/Debugger and saved as

text files with a .m extension similar to script files. All MATLAB built- in mathematical

functions are function m-Files.

A simple function m-File called floan.m is shown in Example 14.1.1. Its main

purpose is to calculate a mathematical function value based on values passed to it from a

script file called Loan_Interest.m and return the computed value to the calling

program. The calling script file Loan_Interest.m is included as well in order to see

where the function calls occur.

Example 14.1.

function i_R = floan(AA,PP,NN,ii) % floan is a function called by the script file 'Loan_Interest.m' % It accepts a monthly payment AA, loan amount PP, a loan duration NN % (in years) and an interest rate ii. It returns a single value % determined from evaluation of the function. The script file % 'Loan_Interest.m' is a root solving program which attempts to find % the root iR of f(A,P,N,i)=0. The user selects from one of two root % solvers, the Bisection Method or the Method of False Position. The % root iR found in 'Loan_Interest.m' is the annualized interest (in % percent).

N_months=12NN; % Convert from years to months if ii~=0 % Check if ii not equal 0 x=1+ii; i_R=AA/PP-(iix^N_months)/(x^N_months-1); % Calculate function % value when ii not equal 0 else % ii equals 0 i_R=AA/PP - 1/N_months % Calculate function value when ii equals 0 end % if ii~=0 % Check if ii not equal 0

% Loan_Interest.m % A script file that calculates the iterest rate on a loan % It calls function floan.m with inputs P,A,N and i % P:Loan amount % A:Monthly installment % N:Duration of loan expressed in years % i:An interest rate (decimal value) % iR: Annual per cent interest rate on loan

%----------------------------------------- clear,clc echo off P=35000; % Loan amount A=750; % Monthly payment N=5; % Loan duration (in years) method='F'; iLinitial=0; iUinitial=1; eSTOP=0.001; iL=iLinitial; iU=iUinitial; fiL=floan(A,P,N,iL); fiU=floan(A,P,N,iU); count=0; i=0; eA=eSTOP+1; while (count<100)&(eA>eSTOP) iold=i;

%%%%% Calculate next i and f(i) %%%%% if method=='B' i=(iL+iU)/2; else i=iU-(fiU*(iL-iU)/(fiL-fiU)); end % if fi=floan(A,P,N,i); inew=i;

%%%%% Determine new endpoint and f(i) at new endpoint %%%%% if fiL*fi< iU=i; fiU=floan(A,P,N,iU); else iL=i; fiL=floan(A,P,N,iL); end % if

%%%%% Caclulate approximate relative error and increment counter %%%%% if count> eA=abs((inew-iold)/inew); end % if count=count+1;

end % while

iR=1200*i; % Calculate annual per cent interest rate fprintf('\n\n')

Example 14.1.

A=1;B=2;

u=0; for i=1: u=u+f1(A,B,i) end % i

z = 0. y = 3. u = 3.

z = 0. y = 5. u = 9.

z = 0. y = 7. u = 17.

function y=f1(A,B,x) % Linear function with noise component y=A+Bx+noise(A) function z=noise(C) % Noise function z=Crand

The subfunction 'noise.m' is invoked by the function 'f1.m' which passes it

the value of variable A, namely 2, to be substituted for variable C wherever it appears in

'noise.m'. Hence, the first output variable calculated is the subfunction variable z

whose value is passed back to the calling function 'f1.m' as the noise component in the

calculation of y. Finally, the numerical value of y is returned to the Command window

program to update variable u.

The comment lines following the function declaration deserve careful

consideration. They will be displayed whenever a help 'function name' command

is issued, usually from the Command window. For example, to obtain a description of

functions 'floan' and 'f1', see Example 14.1.3.

Example 14.1.

help floan % Get description of function floan

floan is a function called by the script file 'Loan_Interest.m' It accepts a loan amount P, a monthly payment A, a loan duration N (in years) and an interest rate i. It returns a single value determined from evaluation of the function. The script file 'Loan_Interest.m' is a root solving program which attempts to find the root iR of f(A,P,N,i)=0. The user selects from one of two root solvers, the Bisection Method or the Method of False Position. The root iR found in 'Loan_Interest.m' is the annualized interest (in percent).

14.2 Input and Output Arguments

There are a number of rules governing the use of input and output arguments in

MATLAB function calls. Several important features are listed below.

1. A function m-File can have zero input and zero output arguments

2. A function can be called with fewer input and output arguments than appear in the

function declaration line.

3. The number of input and output arguments passed to the m-File function can be

determined inside the function by using the MATLAB functions 'nargin' and

'nargout' respectively.

4. A function with outputs in the function declaration line is not required to return

values for all of its outputs. Any output not assigned a value in the body of the m-

File function will not return a value back to where its called from.

Example 14.2.

function [x0,y0]=origin_close(x1,y1,x2,y2,x3,y3,x4,y4) % This functions accepts up to 4 input points (xi,yi) and finds the % one closest to the origin. The coordinates of the closest point to % the origin are returned in the outputs x0 and y switch nargin case 0 disp(' No points searched') case 2 x0=x1;y0=y1; case 4 d1=sqrt(x1x1 + y1y1); d2=sqrt(x2x2 + y2y2); if d1 < d x0=x1;y0=y1; else x0=x2;y0=y2; end % if d1<d case 6 d1=sqrt(x1x1 + y1y1); d2=sqrt(x2x2 + y2y2); d3=sqrt(x3x3 + y3y3); if d1==min([d1,d2,d3]) x0=x1;y0=y1; elseif d2==min([d1,d2,d3]) x0=x2;y0=y2; else x0=x3;y0=y3; end % if d1==min([d1,d2,d3]) case 8 d1=sqrt(x1x1 + y1y1); d2=sqrt(x2x2 + y2y2); d3=sqrt(x3x3 + y3y3); d4=sqrt(x4x4 + y4y4); if d1==min([d1,d2,d3,d4])

x2u=500;y2u=500; x3l=750;y3l=400; x3u=900;y3u=800; road_median(x1l,y1l,x1u,y1u) road_median(x2l,y2l,x2u,y2u) road_median(x3l,y3l,x3u,y3u) road_median(x3l,y3l,x3u,y3u+300)

Warning: One or More Vertex Coordinates Outside of Limits

In C:\MATLABR11\work\Matlab_Course\road_median.m at line 20

0 1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8 0 0 9 0 0 1 0 0 0

0

1 0 0

2 0 0

3 0 0

4 0 0

5 0 0

6 0 0

7 0 0

8 0 0

9 0 0

1 0 0 0

The next example contains a function which draws a traffic signal face at a

location set in the calling script file. The script file also controls the face colors which

are lit by virtue of input argument values passed to the function. The function is listed

below followed by the script file.

Example 14.2.

function TrafficSignal(x,y,visible_g,visible_y,visible_r) %Traffic Signal plots traffic signal with green, yellow or red visible % at location (x,y)

%%% BEGIN PLACEMENT OF TRAFFIC SIGNALS %%%

x_ts_g=x + 10; % x coordinate of traffic signal green light y_ts_g=y - 10; % y coordinate of traffic signal green light x_ts_y=x_ts_g + 2; % x coordinate of traffic signal yellow light y_ts_y=y_ts_g; % y coordinate of traffic signal yellow light x_ts_r=x_ts_y + 2; % x coordinate of traffic signal red light

y_ts_r=y_ts_y; % y coordinate of traffic signal red light x_ts_A=x_ts_g - 2; % x coordinate of traffic signal lower left corner y_ts_A=y_ts_g - 8; % y coordinate of traffic signal lower left corner x_ts_B=x_ts_r + 2; % x coordinate of traffic signal lower right corner y_ts_B=y_ts_A; % y coordinate of traffic signal lower right corner x_ts_C=x_ts_B; % x coordinate of traffic signal upper right corner y_ts_C=y_ts_B + 16; % y coordinate of traffic signal upper right corner x_ts_D=x_ts_A; % x coordinate of traffic signal upper left corner y_ts_D=y_ts_C; % y coordinate of traffic signal upper left corner x_ts=[x_ts_A,x_ts_B,x_ts_C,x_ts_D,x_ts_A]; % Vector of x coordinates of traffic signal corners y_ts=[y_ts_A,y_ts_B,y_ts_C,y_ts_D,y_ts_A]; % Vector of y coordinates of traffic signal corners plot(x_ts,y_ts,'k') % Plot outline of traffic signal hold on plot(x_ts_g,y_ts_g,'o','MarkerSize',40,'MarkerEdgeColor','none','MarkerF aceColor','g','Visible',visible_g) plot(x_ts_y,y_ts_y,'o','MarkerSize',40,'MarkerEdgeColor','none','MarkerF aceColor','y','Visible',visible_y) plot(x_ts_r,y_ts_r,'o','MarkerSize',40,'MarkerEdgeColor','none','MarkerF aceColor','r','Visible',visible_r) axis square axis([32 42 5 25])

%%% END PLACEMENT OF TRAFFIC SIGNALS %%%

% Script file TrafficSignalCall.m % Script file that calls function 'TrafficSignal.m' to position traffic % signal face and control which colors are lit TrafficSignal(25, 25, 'on', 'on', 'on')

3 2 3 4 3 6 3 8 4 0 4 2

5

1 0

1 5

2 0

2 5

  • 1 5 - 1 0 - 5

3 5

3 6

3 7

3 8

3 9

4 0

4 1

4 2

4 3

4 4

4 5

In this example, there are no variables created in the function 'ortho_line' and

the function's workspace would ordinarily be empty. The numerical value of the

MATLAB Workspace variable 'pt' is read by the function but the array itself does not

get copied into the function's workspace. The variable 'm' on the other hand is copied into

the function's workspace because it is modified inside the function.

If necessary, functions can share variables with the MATLAB Workspace if they

are declared global in each workspace.

Example 14.3.

% Script file cyl_call.m % This file calls function cyl.m which returns the volume % of a cylinder with radius R and height h. The radius R % is declared global in both files.

global R R=4; % Set value of global variable h=10; % Input passed to function cyl.m [vol,side]=cyl(h); % Call function cyl.m with input h R,h,vol,side

function [y1,y2]=cyl(h) % This function is called by script file cyl_call.m and calculates the % volume of a cylinder with radius R and height h. The radius R is % global in both files. It also calculates the side of a cube with the % same volume. The volume is returned in output y1 and the cube side % is returned in output y2.

global R y1=pihR^2; % Cylinder volume y2=y1^(1/3); % Side of cube

Running the script file cyl_call results in

R = 4

h = 10 vol = 502. side = 7.