Lesson: Matlab Programs (create and execute Function Files)
write and execute Matlab programs. Also, you'll learn the difference
between a script file and a function file.
is also an M-file, just
like a script file,
but it has a function definition line on the top, that defines the input and output explicitly.
You are about to create a MATLAB
write a function file to draw a circle of a specified radius,
with the radius being the
input of the function. You can either write the function
file from scratch or modify the script file of this
Open the script file prettycircle.m (created and saved before).
On PCs, select 'Open'
from the File menu.
Make sure you're in the correct directory.
Navigate and select the file prettycircle.m
from the 'Open'
dialog box. Double click to open the file. The contents of the program
should appear in an edit
Edit the file prettycircle.m from Tutorial
4 to look like the following:
function [x, y] = prettycirclefn(r)
% CIRCLE - A
script file to draw a pretty circle
% Input: r =
% Output: [x,
y] = the x and y coordinates
angle = linspace(0, 2*pi, 360);
x = r * cos(angle);
y = r * sin(angle);
title(['Radius r =',num2str(r)])
Now, write and save the file under the name prettycirclefn.m as
On PCs, select 'Save As...'
from the 'File'
menu. A dialog box appears.
Type the name of the document as prettycirclefn. Make sure the file is
saved in the folder you want (the current working folder/directory of
MATLAB). Click on the 'Save'
icon to save the file.
In the command window
write the following:
and you get the following figure (see the title):
Then, try the following:
and now you get a circle with radius = 3
Notice that a function file must begin with a function definition line.
In this case is function
[x, y] = prettycirclefn(r), where you define the input
variables and the output ones.
The argument of the 'title'
command in this function file is a combination of
a fixed part
that never changes (the string
'Radius r= '), and a variable
part that depends on the argumments passed on to the
function, and that converts a number into a string (instruction 'num2str').
You can generate now a circle with an arbitrary radius,
and that radius can be assigned to a variable that is used by your
MATLAB program or function!
'Matlab Programs' to
Programs' to 'Matlab Tutorial'