Вы находитесь на странице: 1из 16

5.

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.

5.2 Create Scripts


When you have a sequence of commands to perform repeatedly or that you want to save for
future reference, store them in a program file. The simplest type of MATLAB® program is a
script (Links to an external site.), which contains a set of commands exactly as you would type
them at the command line. For additional programming flexibility, create functions (Links to an
external site.), which accept input and return outputs.

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.

You can create a new script in the following ways:

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

5.3 Create Functions in Files


Both scripts and functions allow you to reuse sequences of commands by storing them in
program files. Scripts are the simplest type of program, since they store commands exactly as
you would type them at the command line. Functions provide more flexibility, primarily because
you can pass input values and return output values. For example, this function named fact
computes the factorial of a number (n) and returns the result (f).

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

Call the script from the command line.

mystats
z =

Syntax for Function Definition

The first line of every function is the definition statement, which includes the following
elements.

function Use lowercase characters for the keyword.


keyword
(required)
Output If your function returns one output, you can specify the output name after the
arguments function keyword.
(optional)
function myOutput = myFunction(x)

If your function returns more than one output, enclose the output names in
square brackets.

function [one,two,three] = myFunction(x)

If there is no output, you can omit it.

function myFunction(x)

Or you can use empty square brackets.

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)

If there are no inputs, you can omit the parentheses.

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.

Contents of Functions and Files

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.

Although it is sometimes optional, use end for better code readability.

5.4 Run Functions in the Editor


This example shows how to run a function that requires some initial setup, such as input
argument values, while working in the Editor.

1. Create a function in a program file named myfunction.m.


2. function y = myfunction(x)
y = x.^2 + x;

This function requires input x.

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)

You can enter multiple commands on the same line, such as

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.

5.5 Conditional Statements


Conditional statements enable you to select at run time which block of code to execute. The
simplest conditional statement is an if (Links to an external site.) statement.

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:

% Generate a random number


a = randi(100, 1);

% 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:

• For numbers, case_expression == switch_expression.


• For character vectors, strcmp(case_expression,switch_expression) == 1.
• For objects that support the eq function, case_expression == switch_expression.
• For a cell array case_expression, at least one of the elements of the cell array matches
switch_expression, as defined above for numbers, character vectors, and objects.

When a case expression is true, MATLAB® executes the corresponding statements and exits the
switch block.

An evaluated switch_expression must be a scalar or character vector. An evaluated


case_expression must be a scalar, a character vector, or a cell array of scalars or character
vectors.

The otherwise block is optional. MATLAB executes the statements only when no case is true.

For example:

[dayNum, dayString] = weekday(date, 'long', 'en_US');

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:

yourNumber = input('Enter a number: ');

if yourNumber < 0
disp('Negative')
elseif yourNumber > 0
disp('Positive')
else
disp('Zero')
end

5.6 Loop Control Statements


With loop control statements, you can repeatedly execute a block of code. There are two types of
loops:

• for (Links to an external site.) statements loop a specific number of times, and keep track
of each iteration with an incrementing index variable.

For example, preallocate a 10-element vector, and calculate five values:

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

Each loop requires the end keyword.

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.

5.7 Add Comments to Programs


When you write code, it is a good practice to add comments that describe the code. Comments
allow others to understand your code, and can refresh your memory when you return to it later.

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,

% Add up all the vector elements.


y = sum(x) % Use the sum function.

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,

header = ['Last Name, ', ...


'First Name, ', ...
... 'Middle Initial, ', ...
'Title']

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.

The Editor does not wrap comments with:

• Code section titles (comments that begin with %%)


• Long contiguous text, such as URLs
• Bulleted list items (text that begins with * or #) onto the preceding line

5.8 Add Help for Your Program


This example shows how to provide help for the programs you write. Help text appears in the
Command Window when you use the help function.

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:

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.

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:

% For more information, see <a href="matlab:


% web('http://www.mathworks.com')">the MathWorks Web site</a>.

End your help text with a blank line (without a %). The help system ignores any comment lines
that appear after the help text block.

5.9 Find Number of Function Arguments


This example shows how to determine how many input or output arguments your function
receives using nargin and nargout.

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

Call addme with one, two, or zero input arguments.

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.

function [result,absResult] = addme2(a,b)


switch nargin
case 2
result = a + b;
case 1
result = a + a;
otherwise
result = 0;
end

if nargout > 1
absResult = abs(result);
end

Call addme2 with one or two output arguments.

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.

5.10 Support Variable Number of Inputs


This example shows how to define a function that accepts a variable number of input arguments
using varargin. The varargin argument is a cell array that contains the function inputs, where
each input is in its own cell.

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.

Call plotWithTitle with two sets of (x,y) inputs and a title.

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.

5.11 Support Variable Number of Outputs


This example shows how to define a function that returns a variable number of output arguments
using varargout. Output varargout is a cell array that contains the function outputs, where
each output is in its own cell.

Create a function in a file named magicfill.m that assigns a magic square to each requested
output.

function varargout = magicfill


nOutputs = nargout;
varargout = cell(1,nOutputs);

for k = 1:nOutputs
varargout{k} = magic(k);
end

Indexing with curly braces {} updates the contents of a cell.

Call magicfill and request three outputs.

[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

function [x,y,varargout] = myfunction(a,b)

In this case, varargout{1} corresponds to the third output that the function returns, and
nargout returns length(varargout) + 2.

Вам также может понравиться