5.1 Programming Basics: The M Files
5.1 Programming Basics: The M Files
5.1 Programming Basics: The M Files
1 Programming Basics
So far, we have used MATLAB environment as a calculator. However, MATLAB is also a
powerful programming language, as well as an interactive computational environment.
In previous chapters, you have learned how to enter commands from the MATLAB command
prompt. MATLAB also allows you to write series of commands into a file and execute the file as
complete unit, like writing a function and calling it.
The M Files
MATLAB allows writing two kinds of program files −
• Scripts − script files are program files with .m extension. In these files, you write series
of commands, which you want to execute together. Scripts do not accept inputs and do
not return any outputs. They operate on data in the workspace.
• Functions − functions files are also program files with .m extension. Functions can
accept inputs and return outputs. Internal variables are local to the function.
You can use the MATLAB editor or any other text editor to create your .m files.
Scripts are the simplest kind of program file because they have no input or output arguments.
They are useful for automating series of MATLAB® commands, such as computations that you
have to perform repeatedly from the command line or series of commands you have to reference.
• Highlight commands from the Command History, right-click, and select Create Script.
• Click the New Script button on the Home tab.
• Use the edit function. For example, edit new_file_name creates (if the file does not
exist) and opens the file new_file_name. If new_file_name is unspecified, MATLAB
opens a new file called Untitled.
After you create a script, you can add code to the script and save it. For example, you can save
this code that generates random numbers between 0 and 100 as a script called numGenerator.m.
columns = 10000;
rows = 1;
bins = columns/100;
rng(now);
list = 100*rand(rows,columns);
histogram(list,bins)
Save your script and run the code using either of these methods:
• Type the script name on the command line and press Enter. For example, to run the
numGenerator.m script, type numGenerator.
• Click the Run button on the Editor tab
You also can run the code from a second program file. To do this, add a line of code with the
script name to the second program file. For example, to run the numGenerator.m script from a
second program file, add the line numGenerator; to the file. MATLAB runs the code in
numGenerator.m when you run the second file.
When execution of the script completes, the variables remain in the MATLAB workspace. In the
numGenerator.m example, the variables columns, rows, bins, and list remain in the
workspace. To see a list of variables, type whos at the command prompt. Scripts share the base
workspace with your interactive MATLAB session and with other scripts.
function f = fact(n)
f = prod(1:n);
end
This type of function must be defined within a file, not at the command line. Often, you store a
function in its own file. In that case, the best practice is to use the same name for the function
and the file (in this example, fact.m), since MATLAB® associates the program with the file
name. Save the file either in the current folder or in a folder on the MATLAB search path.
You can call the function from the command line, using the same syntax rules that apply to
functions installed with MATLAB. For instances, calculate the factorial of 5.
x = 5;
y = fact(5)
y =
120
Starting in R2016b, another option for storing functions is to include them at the end of a script
file. For instance, create a file named mystats.m with a few commands and two functions, fact
and perm. The script calculates the permutation of (3,2).
x = 3;
y = 2;
z = perm(x,y)
function p = perm(n,r)
p = fact(n)*fact(n-r);
end
function f = fact(n)
f = prod(1:n);
end
mystats
z =
The first line of every function is the definition statement, which includes the following
elements.
If your function returns more than one output, enclose the output names in
square brackets.
function myFunction(x)
function [] = myFunction(x)
Function Valid function names follow the same rules as variable names. They must start
name with a letter, and can contain letters, digits, or underscores.
(required)
Note: To avoid confusion, use the same name for both the function file and
the first function within the file. MATLAB associates your program with the
file name, not the function name. Script files cannot have the same name as a
function in the file.
Input If your function accepts any inputs, enclose their names in parentheses after the
arguments function name. Separate inputs with commas.
(optional)
function y = myFunction(one,two,three)
Tip: When you define a function with multiple input or output arguments, list any required
arguments first. This ordering allows you to call your function without specifying optional
arguments.
The body of a function can include valid MATLAB expressions, control flow statements,
comments, blank lines, and nested functions. Any variables that you create within a function are
stored within a workspace specific to that function, which is separate from the base workspace.
Program files can contain multiple functions. If the file contains only function definitions, the
first function is the main function, and is the function that MATLAB associates with the file
name. Functions that follow the main function or script code are called local functions. Local
functions are only available within the file.
End Statements
Functions end with either an end (Links to an external site.) statement, the end of the file, or the
definition line for a local function, whichever comes first. The end statement is required if:
• Any function in the file contains a nested function (a function completely contained
within its parent).
• The function is a local function within a function file, and any local function in the file
uses the end keyword.
• The function is a local function within a script file.
3. View the commands available for running the function by clicking Run on the Editor
tab. The command at the top of the list is the command that the Editor uses by default
when you click the Run icon.
4. Replace the text type code to run with an expression that allows you to run the function.
y = myfunction(1:10)
x = 1:10; y = myfunction(x)
For more complicated, multiline commands, create a separate script file, and then run the
script.
Note: Run commands use the base workspace. Any variables that you define in a run
command can overwrite variables in the base workspace that have the same name.
5. Run the function by clicking Run or a specific run command from the drop-down list.
For myfunction.m, and an input of 1:10, this result appears in the Command Window:
6. y =
2 6 12 20 30 42 56 72 90 110
When you select a run command from the list, it becomes the default for the Run button.
To edit or delete an existing run command, select the command, right-click, and then select Edit
or Delete.
Syntax
if expression
statements
elseif expression
statements
else
statements
end
Description
if expression, statements, end evaluates an expression (Links to an external site.), and
executes a group of statements when the expression is true. An expression is true when its result
is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the
expression is false.
The elseif and else blocks are optional. The statements execute only if previous expressions in
the if...end block are false. An if block can include multiple elseif blocks.
For example:
% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end
if statements can include alternate choices, using the optional keywords elseif or else. For
example:
a = randi(100, 1);
if a < 30
disp('small')
elseif a < 80
disp('medium')
else
disp('large')
end
Alternatively, when you want to test for equality against a set of known values, use a
switch (Links to an external site.) statement.
Syntax
switch switch_expression
case case_expression
statements
case case_expression
statements ...
otherwise
statements
end
Description
switch switch_expression, case case_expression, end evaluates an expression and
chooses to execute one of several groups of statements. Each choice is a case.
The switch block tests each case until one of the case expressions is true. A case is true when:
When a case expression is true, MATLAB® executes the corresponding statements and exits the
switch block.
The otherwise block is optional. MATLAB executes the statements only when no case is true.
For example:
switch dayString
case 'Monday'
disp('Start of the work week')
case 'Tuesday'
disp('Day 2')
case 'Wednesday'
disp('Day 3')
case 'Thursday'
disp('Day 4')
case 'Friday'
disp('Last day of the work week')
otherwise
disp('Weekend!')
end
For both if and switch, MATLAB® executes the code corresponding to the first true condition,
and then exits the code block. Each conditional statement requires the end keyword.
In general, when you have many possible discrete, known values, switch statements are easier
to read than if statements. However, you cannot test for inequality between switch and case
values. For example, you cannot implement this type of condition with a switch:
if yourNumber < 0
disp('Negative')
elseif yourNumber > 0
disp('Positive')
else
disp('Zero')
end
• for (Links to an external site.) statements loop a specific number of times, and keep track
of each iteration with an incrementing index variable.
x = ones(1,10);
for n = 2:6
x(n) = 2 * x(n - 1);
end
• while (Links to an external site.) statements loop as long as a condition remains true.
For example, find the first integer n for which factorial(n) is a 100-digit number:
n = 1;
nFactorial = 1;
while nFactorial < 1e100
n = n + 1;
nFactorial = nFactorial * n;
end
It is a good idea to indent the loops for readability, especially when they are nested (that is, when
one loop contains another loop):
A = zeros(5,100);
for m = 1:5
for n = 1:100
A(m, n) = 1/(m + n - 1);
end
end
You can programmatically exit a loop using a break (Links to an external site.) statement, or
skip to the next iteration of a loop using a continue (Links to an external site.) statement. For
example, count the number of lines in the help for the magic function (that is, all comment lines
until a blank line):
fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
line = fgetl(fid);
if isempty(line)
break
elseif ~strncmp(line,'%',1)
continue
end
count = count + 1;
end
fprintf('%d lines in MAGIC help\n',count);
fclose(fid);
Tip: If you inadvertently create an infinite loop (a loop that never ends on its own), stop
execution of the loop by pressing Ctrl+C.
Add comments to MATLAB® code using the percent (%) symbol. Comment lines can appear
anywhere in a program file, and you can append comments to the end of a line of code. For
example,
In live scripts, you can also describe a process or code by inserting lines of text before and after
code. Text lines provide additional flexibility such as standard formatting options, and the
insertion of images, hyperlinks, and equations. For more information, see Create Live
Scripts (Links to an external site.).
Note: When you have a MATLAB code file (.m) containing text that has characters in a
different encoding than that of your platform, when you save or publish your file, MATLAB
displays those characters as garbled text. Live scripts (.mlx) support storing and displaying
characters across all locales.
Comments are also useful for program development and testing—comment out any code that
does not need to run. To comment out multiple lines of code, you can use the block comment
operators, %{ and %}:
a = magic(3);
%{
sum(a)
diag(a)
sum(diag(a))
%}
sum(diag(fliplr(a)))
The %{ and %} operators must appear alone on the lines that immediately precede and follow the
block of help text. Do not include any other text on these lines.
To comment out part of a statement that spans multiple lines, use an ellipsis (...) instead of a
percent sign. For example,
The MATLAB Editor includes tools and context menu items to help you add, remove, or change
the format of comments for MATLAB, Java®, and C/C++ code. For example, if you paste
lengthy text onto a comment line, such as
% This is a program that has a comment that is a little more than 75 columns
wide.
disp('Hello, world')
and then press the button next to Comment on the Editor or Live Editor tab, the Editor
wraps the comment:
% This is a program that has a comment that is a little more than 75
% columns wide.
disp('Hello, world')
By default, as you type comments in the Editor, the text wraps when it reaches a column width of
75. To change the column where the comment text wraps, or to disable automatic comment
wrapping, adjust the Editor/Debugger Language preference settings labeled Comment
formatting.
Create help text by inserting comments at the beginning of your program. If your program
includes a function, position the help text immediately below the function definition line (the line
with the function keyword).
For example, create a function in a file named addme.m that includes help text:
function c = addme(a,b)
% ADDME Add two values together.
% C = ADDME(A) adds A to itself.
% C = ADDME(A,B) adds A and B together.
%
% See also SUM, PLUS.
switch nargin
case 2
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end
When you type help addme at the command line, the help text displays in the Command
Window:
The first help text line, often called the H1 line, typically includes the program name and a brief
description. The Current Folder browser and the help and lookfor functions use the H1 line to
display information about the program.
Create See also links by including function names at the end of your help text on a line that
begins with % See also. If the function exists on the search path or in the current folder, the
help command displays each of these function names as a hyperlink to its help. Otherwise, help
prints the function names as they appear in the help text.
You can include hyperlinks (in the form of URLs) to Web sites in your help text. Create
hyperlinks by including an HTML <a></a> anchor element. Within the anchor, use a matlab:
statement to execute a web command. For example:
End your help text with a blank line (without a %). The help system ignores any comment lines
that appear after the help text block.
Input Arguments
Create a function in a file named addme.m that accepts up to two inputs. Identify the number of
inputs with nargin.
function c = addme(a,b)
switch nargin
case 2
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end
addme(42)
ans =
84
addme(2,4000)
ans =
4002
addme
ans =
0
Output Arguments
Create a new function in a file named addme2.m that can return one or two outputs (a result and
its absolute value). Identify the number of requested outputs with nargout.
if nargout > 1
absResult = abs(result);
end
value = addme2(11,-22)
value =
-11
[value,absValue] = addme2(11,-22)
value =
-11
absValue =
11
Functions return outputs in the order they are declared in the function definition.
Create a function in a file named plotWithTitle.m that accepts a variable number of paired
(x,y) inputs for the plot function and an optional title. If the function receives an odd number of
inputs, it assumes that the last input is a title.
function plotWithTitle(varargin)
if rem(nargin,2) ~= 0
myTitle = varargin{nargin};
numPlotInputs = nargin - 1;
else
myTitle = 'Default Title';
numPlotInputs = nargin;
end
plot(varargin{1:numPlotInputs})
title(myTitle)
Because varargin is a cell array, you access the contents of each cell using curly braces, {}. The
syntax varargin{1:numPlotInputs} creates a comma-separated list of inputs to the plot
function.
x = [1:.1:10];
y1 = sin(x);
y2 = cos(x);
plotWithTitle(x,y1,x,y2,'Sine and Cosine')
You can use varargin alone in an input argument list, or at the end of the list of inputs, such as
function myfunction(a,b,varargin)
In this case, varargin{1} corresponds to the third input passed to the function, and nargin
returns length(varargin) + 2.
Create a function in a file named magicfill.m that assigns a magic square to each requested
output.
for k = 1:nOutputs
varargout{k} = magic(k);
end
[first,second,third] = magicfill
first =
1
second =
1 3
4 2
third =
8 1 6
3 5 7
4 9 2
MATLAB® assigns values to the outputs according to their order in the varargout array. For
example, first == varargout{1}.
You can use varargout alone in an output argument list, or at the end of the list of outputs, such
as
In this case, varargout{1} corresponds to the third output that the function returns, and
nargout returns length(varargout) + 2.