0% found this document useful (0 votes)
0 views

Script and function files in MATLAB

Uploaded by

Thanh Phúc Hồ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Script and function files in MATLAB

Uploaded by

Thanh Phúc Hồ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Introduction to Computer for Engineers

Scripts and function files


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


Scripts:
➢share the base workspace with your interactive Matlab
session and with other scripts.
➢operate on existing data in the workspace
➢can 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
Running a script can unintentionally
overwrite data stored in the base workspace
by commands entered at the Matlab
command prompt.
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.
➢ 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.

• 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 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” 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.
➢ a function accepts input from and returns
output to its caller, whereas scripts do not.
→You 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, …);
• 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
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
• 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
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
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 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.
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.

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


3. 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
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). 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”.
 function z = fun(x,y)
 u = 3*x;
 z = u + 6*y.^2;
 >>x = 3; y = 7;
 >>z = fun(x,y)
 z=
 303
 or
 >>z = fun(3,7)
 z=
 303
 function [A, C] = circle(r)
 A = pi*r.^2;
 C = 2*pi*r;
 The function is called as follows, if r 4.
 >>[A, C] = circle(4)
 A=
 50.2655
 C=
 25.1327
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.
Example
1. Problem Definition
Write a function that computes the time for a falling object to hit the ground.
2. 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 is a quadratic formula in terms of the variable time. This can be solved to give:

− velocity _ 0  velocity _ 0 2 − 2 * g * height _ 0


time =
g
User inputs: initial height (height_t) and initial velocity (velocity_0)
User outputs: time to hit ground (time)
3. 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
− velocity _ 0  velocity _ 0 2 − 2 * g * height _ 0
time =
g

Check to see if the values make sense

Output to the user the calculated


Time values
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” .
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)
1. Write a script to calculate the hypotenuse of a square
triangle.

2. Write a function to calculate the hypotenuse of a


square triangle.

3. Write a function to calculate the sum, product and


average of five numbers.
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