Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Lecture 3-Script and Function

This document provides an overview of MATLAB scripts and functions. MATLAB scripts are text files with the .m extension that contain MATLAB commands that are executed sequentially when the file name is called. Scripts share a common workspace. MATLAB function files also end in .m but contain function definitions with inputs and outputs. Functions have their own private workspace and are reusable modules. Well-designed functions promote modular programming.

Uploaded by

Viet Pham
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Lecture 3-Script and Function

This document provides an overview of MATLAB scripts and functions. MATLAB scripts are text files with the .m extension that contain MATLAB commands that are executed sequentially when the file name is called. Scripts share a common workspace. MATLAB function files also end in .m but contain function definitions with inputs and outputs. Functions have their own private workspace and are reusable modules. Well-designed functions promote modular programming.

Uploaded by

Viet Pham
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

LECTURE 3: SCRIPTS AND

FUNCTIONS

1
2

CONTENTS

MATLAB SCRIPTS
MATLAB FUNCTION FILES
M AT L A B S C R I P T S

 A MATLAB script file (Called an M-file) is a text (plain ASCII) file that contains one or more

MATLAB commands and, optionally, comments.


 The file is saved with the extension ".m".
 When the filename (without the extension) is issued as a command in MATLAB, the file is

opened, read, and the commands are executed as if input from the keyboard.
 There is no input or output arguments.
T H E B A S E W O R K S PA C E

Scripts:
 Share the base workspace with your interactive Matlab session and with other scripts.
 Operate on existing data in the workspace
 Create new data on which to operate.
Any variables that scripts create remain in the workspace after the script finishes so you can use
them for further computations
SIMPLE SCRIPT EXAMPLE

Running a script can unintentionally

overwrite data stored in the base workspace

by commands entered at the Matlab

command prompt.
M AT L A B S C R I P T S
 Example 1. Calculate rho for several trigonometric functions of theta, then create a series of
polar plots:
% A script to produce % Comment lines % "flower petal" plots
theta = -pi:0.01:pi; % Computations
rho(1,:) = 2 * sin(5 * theta) .^ 2;
rho(2,:) = cos(10 * theta) .^ 3;
rho(3,:) = sin(theta) .^ 2;
rho(4,:) = 5 * cos(3.5 * theta) .^ 3;
for k = 1:4
polar(theta, rho(k,:)) % Graphics output
pause
end
Enter these commands in a file called petals.m. MATLAB script Type petals at the
MATLAB command line  executes the statements in the script.
M AT L A B F U N C T I O N F I L E S

 A MATLAB function file (called an M-file) is a text (plain ASCII) file that contains a MATLAB
function and, optionally, comments.
 The file is saved with the function name and the usual MATLAB script file extension, ".m".
 A MATLAB function may be called from the command line or from any other M-file.
 When the function is called in MATLAB, the file is accessed, the function is executed, and
control is returned to the MATLAB workspace.
 Since the function is not part of the MATLAB workspace, its variables and their values are not
known after control is returned.
M AT L A B F U N C T I O N F I L E S ( C O N T. )

 Any values to be returned must be specified in the function syntax.


 A Matlab function like a mathematical function is a rule where given a certain input or outputs,
the rule tells how to compute the output value or how to produce an effect.
 The inputs are called the “arguments” of the function.
 Functions always begin with a function definition Line and end either with the first matching end
statement, the occurrence of another function definition line, or the end of the file, whichever
comes first.
 Using end to mark the end of a function definition is required only when the function being
defined contains one or more nested functions.
SCRIPTS VS FUNCTION FILES
A function accepts input from and returns output to its caller, whereas scripts do not.
 Define MATLAB functions in a file that begins with a line containing the function key word.
→ You cannot define a function within a script file or at the MATLAB command line.

The syntax for a MATLAB function definition is:


- function [val1, … , valn] = myfunc (arg1, … , argk)
 where val1 through valn are the specified returned values from the function and arg1 through argk are the values
sent to the function.

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, …);
M AT L A B F U N C T I O N F I L E S ( C O N T. )

 Since variables are local in MATLAB the function has its own memory locations for all of the
variables and only the values (not their addresses) are passed between the MATLAB workspace
and the function.
 Functions operate on variables within their own workspace.
 This workspace is separated from the base workspace; the workspace that you access at the
MATLAB command prompt and in scripts.
 Each function in a file has an area of memory, separate from the MATLAB base workspace, in
which it operates.
 This area, called the function workspace, gives each function its own workspace context.
EXAMPLE OF WRITING FUNCTION
function [ a , b ] = swap ( a , b )
% The function swap receives two values, swaps them,
temp=a;
a=b;
b=temp;
End

function [ r , g ] = swap ( c , d )
% The function swap receives two values, swaps them,
r=d;
g=c;
end
M AT L A B F U N C T I O N F I L E S ( C O N T. )

 To use the function a MATLAB program could assign values to two variables (the names do not
have to be a and b) and then call the function to swap them. For instance the MATLAB
commands:
>> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y )
result in:
x=
6
y=
5
M AT L A B F U N C T I O N F I L E S ( C O N T. )
 function [output_variable1, output_variable2, …] = function_name(input_variable1,input_variable2, …)
 % 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: In the body of the function you MUST define all of the output variables or Matlab will give you an error
M AT L A B F U N C T I O N F I L E S ( C O N T. )

 Why write “functions” instead of “scripts”?


 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

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.
M AT L A B F U N C T I O N F I L E S ( C O N T. )

 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.
PROGRAMMING STEPS

1. Problem Definition
2. Analyze the problems
(i.e. write down the appropriate equations, determine the user input and user output, ….)
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
EXAMPLE 1

 Problem Definition
Write a function that converts a temperature in Fahrenheit to Celsius.
 Problem Analysis
 User to input a temperature in Fahrenheit
 Output to the user temperature in Celsius
Use the fact that celsius = (fahr - 32) * 5/9
E X A M P L E 1 ( C O N T. )

 Develop Algorithm (processing steps to solve problem)


User inputs a single number
or vector of numbers that
represent temperature in Fahrenheit
Assign those temperatures to the variable
“fahr”

Calculate a new variable called “celsius”


Using the following formula
celsius = (fahr - 32) * 5/9

Output to the user the calculated


temperatures in celsius
E X A M P L E 1 ( C O N T. )

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).
 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”.
E X A M P L E 1 ( C O N T. )
EXAMPLES
 function z = fun(x,y) function [A, C] = circle(r)
u = 3*x; A = pi*r.^2;

z = u + 6*y.^2; C = 2*pi*r;

>>x = 3; y = 7; The function is called as follows, if r=4.

>>z = fun(x,y) >>[A, C] = circle(4)

z =303 A =50.2655

or C =25.1327

>>z = fun(3,7)
z =303
EXAMPLE

 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)
 Run Code
 Since two points determine a linear function we know the function F_to_C works correctly.
EXAMPLE
EXAMPLE 2
Problem Definition
Write a function that computes the time for a falling object to hit the ground.
 Problem Analysis
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 = height_0 + velocity_0 * time + 1/2 * g * time * time

This can be solved to give:


User inputs: initial height (height_t) and initial velocity (velocity_0)
User outputs: time to hit ground (time)
E X A M P L E 2 ( C O N T. )
Develop Algorithm (processing steps to solve problem)
User inputs two single number
or vector of numbers that
represent the initial height of the object
(height_0), and initial velocity (velocity_0)

Calculate a new variable called time


Using the following formula

Check to see if the values make sense

Output to the user the calculated


Time values
E X A M P L E 2 ( C O N T. )

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” .
E X A M P L E 2 ( C O N T. )

Test and debug 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)
PRACTICAL EXERCISE 1
1. Let x = -5-j8 and y = 10-j5. Use Matlab to compute the following expressions:
a. The magnitude and angle of x.y
b. The magnitude and angle of x/y

2. Use Matlab to find the angles corresponding to the following coordinates:


a. (x,y)=(5,8)
b. (x,y)=(-5,-8)

You might also like