Script and function files in MATLAB
Script and function files in MATLAB
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.
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 –
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
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:
This is a quadratic formula in terms of the variable time. This can be solved to give: