The Language of Technical Computing

32
Product Description The Language of Technical Computing MATLAB is a high-level language and interactive environment for numerical computation, visualization, and programming. Using MATLAB, you can analyze data, develop algorithms, and create models and applications. The language, tools, and built-in math functions enable you to explore multiple approaches and reach a solution faster than with spreadsheets or traditional programming languages, such as C/C++ or Java™. You can use MATLAB for a range of applications, including signal processing and communications, image and video processing, control systems, test and measurement, computational finance, and computational biology. More than a million engineers and scientists in industry and academia use MATLAB, the language of technical computing. Key Features High-level language for numerical computation, visualization, and application development Interactive environment for iterative exploration, design, and problem solving Mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration, and solving ordinary differential equations Built-in graphics for visualizing data and tools for creating custom plots Development tools for improving code quality and maintainability and maximizing performance Tools for building applications with custom graphical interfaces

description

technical computing

Transcript of The Language of Technical Computing

Page 1: The Language of Technical Computing

Product Description

The Language of Technical Computing

MATLAB is a high-level language and interactive environment for numerical computation, visualization, and programming. Using MATLAB, you can analyze data, develop algorithms, and create models and applications. The language, tools, and built-in math functions enable you to explore multiple approaches and reach a solution faster than with spreadsheets or traditional programming languages, such as C/C++ or Java™. You can use MATLAB for a range of applications, including signal processing and communications, image and video processing, control systems, test and measurement, computational finance, and computational biology. More than a million engineers and scientists in industry and academia use MATLAB, the language of technical computing.

Key Features High-level language for numerical computation, visualization, and application

development

Interactive environment for iterative exploration, design, and problem solving

Mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration, and solving ordinary differential equations

Built-in graphics for visualizing data and tools for creating custom plots

Development tools for improving code quality and maintainability and maximizing performance

Tools for building applications with custom graphical interfaces

Functions for integrating MATLAB based algorithms with external applications and languages such as C, Java, .NET, and Microsoft® Excel®

Desktop Basics

When you start MATLAB, the desktop appears in its default layout.

The desktop includes these panels:

Current Folder — Access your files.

Command Window — Enter commands at the command line, indicated by the prompt (>>).

Workspace — Explore data that you create or import from files.

Page 2: The Language of Technical Computing

Command History — View or rerun commands that you entered at the command line.

As you work in MATLAB, you issue commands that create variables and call functions. For example, create a variable named a by typing this statement at the command line:a = 1

MATLAB adds variable a to the workspace and displays the result in the Command Window.a =

1

Create a few more variables.b = 2b =

2c = a + bc =

3d = cos(a)d =

0.5403

When you do not specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of your calculation.sin(a)ans =

0.8415

If you end a statement with a semicolon, MATLAB performs the computation, but suppresses the display of output in the Command Window.e = a*b;

You can recall previous commands by pressing the up- and down-arrow keys, ↑ and ↓. Press the arrow keys either at an empty command line or after you type the first few characters of a command. For example, to recall the command b = 2, type b, and then press the up-arrow key.

Search MATLAB Documentation

R2012b

MATLAB

Language Fundamentals

Page 3: The Language of Technical Computing

Entering Commands

formatSet display format for output

Syntax format example

format Style example

Descriptionexample

format sets the display of floating-point numeric values to the default display format, which is the short fixed decimal format. This format displays 5-digit scaled, fixed-point values.

The format function affects only how numbers display in the Command Window, not how MATLAB computes or saves them.

example

format Style changes the display format to the specified Style.

Examplescollapse all

Change and View Current FormatSet the display format to long fixed decimal.format long

View the result for the value of pi.pians =

3.141592653589793

View the current format.get(0,'format')ans =

long

Page 4: The Language of Technical Computing

Display Values in Default and Hexadecimal FormatSet the format to its default, and display the maximum values for integers and real numbers in MATLAB.format

intmax('uint64')ans =

18446744073709551615realmaxans = 1.7977e+308

Change the display format to hexadecimal, and then display the same values.format hex

intmax('uint64')ans =

ffffffffffffffffrealmaxans =

7fefffffffffffff

The hexadecimal display corresponds to the internal representation of the value. It is not the same as the hexadecimal notation in the C programming language.

View Output in Short and Long Engineering NotationView the difference between output displayed in the shortEng and longEng formats.

Set the display format to shortEng.format shortEng

Create variable A and increase its value by a multiple of 10 each time through a for loop. Display each value of A.A = 5.123456789;for k=1:10 disp(A) A = A * 10;end 5.1235e+000 51.2346e+000 512.3457e+000 5.1235e+003 51.2346e+003 512.3457e+003 5.1235e+006 51.2346e+006 512.3457e+006 5.1235e+009

Page 5: The Language of Technical Computing

The values for A display with 4 digits after the decimal point, and an exponent that is a multiple of 3.

Set the display format to longEng and view the same values of A.format longEng

A = 5.123456789;for k=1:10 disp(A) A = A * 10;end 5.12345678900000e+000 51.2345678900000e+000 512.345678900000e+000 5.12345678900000e+003 51.2345678900000e+003 512.345678900000e+003 5.12345678900000e+006 51.2345678900000e+006 512.345678900000e+006 5.12345678900000e+009

The values for A display with 15 digits, and an exponent that is a multiple of 3.

Display Large Data Range in short and shortg FormatsView the difference between the short and shortg formats when the values in a matrix span a wide range.

Define variable x and display the output in the short format.x = [25 56 255 9876899999];format shortxx = 1.0e+09 * 0.0000 0.0000 0.0000 9.8769

The display indicates each value is multiplied by 1.0e+09.

Set the format to shortg and redisplay x.format shortgxx = 25 56 255 9.8769e+09

Input Argumentscollapse all

Style — Output display format short (default) | long | shortE | longE | ...Output display format, specified as one of the strings listed in the tables that follow.

Page 6: The Language of Technical Computing

Use these styles to switch between different output display formats for floating-point variables. Styles are case insensitive. You also can insert a space between short or long and the presentation type, for instance, format short E.

Style Result Example

short (default)

Short fixed decimal format, with 4 digits after the decimal point.

If you are displaying a matrix with a wide range of values, consider using shortG. See Display Large Data Range in short and shortg Formats

3.1416

longLong fixed decimal format, with 15 digits after the decimal point for double values, and 7 digits after the decimal point for single values.

3.141592653589793

short

E

Short scientific notation, with 4 digits after the decimal point.

Integer-valued floating-point numbers with a maximum of 9 digits do not display in scientific notation.

3.1416e+00

longE

Long scientific notation, with 15 digits after the decimal point for double values, and 7 digits after the decimal point for single values.

Integer-valued floating-point numbers with a maximum of 9 digits do not display in scientific notation.

3.141592653589793e+00

shortG The more compact of short fixed decimal or scientific notation, with 5 digits. 3.1416

longG The more compact of long fixed decimal or scientific notation, with 15 digits for double values, and 7 digits for single values.

3.14159265358979

shortEng

Short engineering notation, with 4 digits after the decimal point, and an exponent that is a multiple of 3.

3.1416e+000

longEng

Long engineering notation, with 15 significant digits, and an exponent that is a multiple of 3.

3.14159265358979e+000

Use these format styles to switch between different output display formats for all numeric variables.

Style

Result Example

+ Positive/Negative format, with +, -, and blank characters displayed for positive, negative, and zero elements.

+

bank Currency format, with 2 digits after the decimal point. 3.14

he Hexadecimal representation of a binary double-precision number. 400921f

Page 7: The Language of Technical Computing

x b54442d18

rat Ratio of small integers. 355/113

Use these format styles to affect the spacing in the display of all variables.

DispType

ResultExampl

e

compact

Suppresses excess line feeds to show more output in a single screen. Contrast with loose.

theta = pi/2theta =1.5708

loose Adds linefeeds to make output more readable. Contrast with compact.

theta = pi/2

theta =

1.5708

More Aboutexpand all

Tips The specified format applies only to the current MATLAB session. To maintain a

format across sessions, choose a Numeric format or Numeric display option in the Command Window Preferences.

To see which Style is currently in use, typeget(0,'Format')

To see if compact or loose formatting is currently selected, typeget(0,'FormatSpacing')

AlgorithmsMATLAB always displays integer variables to the appropriate number of digits for the class. For example, MATLAB uses 3 digits to display numbers of type int8 (for example, -128:127). Setting format to short or long does not affect the display of integer variables.

If the largest element of a matrix is larger than 103 or smaller than 10-3, then MATLAB applies a common scale factor for the short and long formats.

Format Output in Command Window

Page 8: The Language of Technical Computing

Extras: Introduction to M-files

Contents

What is an m-file?

Why use m-files?

How to create, save or open an m-file?

How to run the m-file?

What is an m-file?

An m-file, or script file, is a simple text file where you can place MATLAB commands. When the file is run,

MATLAB reads the commands and executes them exactly as it would if you had typed each command

sequentially at the MATLAB prompt. All m-file names must end with the extension '.m' (e.g. test.m). If you

create a new m-file with the same name as an existing m-file, MATLAB will choose the one which appears

first in the path order (type help path in the command window for more information). To make life easier,

choose a name for your m-file which doesn't already exist. To see if a filename.m already exists, type

help filename at the MATLAB prompt.

Why use m-files?

For simple problems, entering your requests at the MATLAB prompt is fast and efficient. However, as the

number of commands increases or trial and error is done by changing certain variables or values, typing the

commands over and over at the MATLAB prompt becomes tedious. M-files will be helpful and almost

necessary in these cases.

How to create, save or open an m-file?

If you are using PC or Mac:

Page 9: The Language of Technical Computing

To create an m-file, choose New from the File menu and select Script. This procedure brings up a text

editor window in which you can enter MATLAB commands.

To save the m-file, simply go to the File menu and choose Save (remember to save it with the '.m'

extension). To open an existing m-file, go to the File menu and choose Open.

If you are using Unix:

To create an m-file, use your favorite text editor (pico, nedit, vi, emacs, etc.) to create a file with .m

extension (e.g. filename.m).

How to run the m-file?

After the m-file is saved with the name filename.m in the current MATLAB folder or directory, you can

execute the commands in the m-file by simply typing filename at the MATLAB command window prompt.

Scripts vs. Functions

This topic discusses the differences between scripts and functions, and shows how to convert a script to a function.

Program files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output. Both scripts and functions contain MATLAB code, and both are stored in text files with a .m extension. However, functions are more flexible and more easily extensible.

For example, create a script in a file named triarea.m that computes the area of a triangle:b = 5;h = 3;a = 0.5*(b.* h)

After you save the file, you can call the script from the command line:triareaa = 7.5000

Page 10: The Language of Technical Computing

To calculate the area of another triangle using the same script, you could update the values of b and h in the script and rerun it. Each time you run it, the script stores the result in a variable named a that is in the base workspace.

However, instead of manually updating the script each time, you can make your program more flexible by converting it to a function. Replace the statements that assign values to b and h with a function declaration statement. The declaration includes the function keyword, the names of input and output arguments, and the name of the function.function a = triarea(b,h)a = 0.5*(b.* h);

After you save the file, you can call the function with different base and height values from the command line without modifying the script:a1 = triarea(1,5)a2 = triarea(2,10)a3 = triarea(3,6)a1 = 2.5000a2 = 10a3 = 9

Functions have their own workspace, separate from the base workspace. Therefore, none of the calls to the function triarea overwrite the value of a in the base workspace. Instead, the function assigns the results to variables a1, a2, and a3.

Base and Function Workspaces

This topic explains the differences between the base workspace and function workspaces, including workspaces for local functions, nested functions, and scripts.

The base workspace stores variables that you create at the command line. This includes any variables that scripts create, assuming that you run the script from the command line or from the Editor. Variables in the base workspace exist until you clear them or end your MATLAB session.

Functions do not use the base workspace. Every function has its own function workspace. Each function workspace is separate from the base workspace and all other workspaces to protect the integrity of the data. Even local functions in a common file have their own workspaces. Variables specific to a function workspace are called local variables. Typically, local variables do not remain in memory from one function call to the next.

When you call a script from a function, the script uses the function workspace.

Like local functions, nested functions have their own workspaces. However, these workspaces are unique in two significant ways:

Page 11: The Language of Technical Computing

Nested functions can access and modify variables in the workspaces of the functions that contain them.

All of the variables in nested functions or the functions that contain them must be explicitly defined. That is, you cannot call a function or script that assigns values to variables unless those variables already exist in the function workspace.

functionDeclare function name, inputs, and outputs

Syntax function [y1,...,yN] = myfun(x1,...,xM) example

Descriptionexample

function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that accepts inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first executable line of the function.

Save the function code in a text file with a .m extension. The name of the file should match the name of the first function in the file. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

You can declare multiple local functions within the same file, or nest functions. If any function in a file contains a nested function, all functions in the file must use the end keyword to indicate the end of the function. Otherwise, the end keyword is optional.

Examplesexpand all

Function with One OutputDefine a function in a file named average.m that accepts an input vector, calculates the average of the values, and returns a single result.function y = average(x)if ~isvector(x) error('Input must be a vector')endy = sum(x)/length(x);

Call the function from the command line.z = 1:99;average(z)

Page 12: The Language of Technical Computing

ans = 50

Function with Multiple OutputsDefine a function in a file named stat.m that returns the mean and standard deviation of an input vector.function [m,s] = stat(x)n = length(x);m = sum(x)/n;s = sqrt(sum((x-m).^2/n));

Call the function from the command line.values = [12.7, 45.4, 98.9, 26.6, 53.1];[ave,stdev] = stat(values)ave = 47.3400stdev = 29.4124

Multiple Functions in a FileDefine two functions in a file named stat2.m, where the first function calls the second.function [m,s] = stat2(x)n = length(x);m = avg(x,n);s = sqrt(sum((x-m).^2/n));end

function m = avg(x,n)m = sum(x)/n;end

Function avg is a local function. Local functions are only available to other functions within the same file.

Call function stat2 from the command line.values = [12.7, 45.4, 98.9, 26.6, 53.1];[ave,stdev] = stat2(values)ave = 47.3400stdev = 29.4124

Create Functions in Files

More About Local Functions

Nested Functions

Base and Function Workspaces

Function Precedence Order

Page 13: The Language of Technical Computing

Local Functions

This topic explains the term local function, and shows how to create and use local functions.

MATLAB program files can contain code for more than one function. The first function in the file (the main function) is visible to functions in other files, or you can call it from the command line. Additional functions within the file are called local functions. Local functions are only visible to other functions in the same file. They are equivalent to subroutines in other programming languages, and are sometimes called subfunctions.

Local functions can occur in any order, as long as the main function appears first. Each function begins with its own function definition line.

For example, create a program file named mystats.m that contains a main function, mystats, and two local functions, mymean and mymedian.function [avg, med] = mystats(x)n = length(x);avg = mymean(x,n);med = mymedian(x,n);end

function a = mymean(v,n)% MYMEAN Example of a local function.

a = sum(v)/n;end

function m = mymedian(v,n)% MYMEDIAN Another example of a local function.

w = sort(v);if rem(n,2) == 1 m = w((n + 1)/2);else m = (w(n/2) + w(n/2 + 1))/2;endend

The local functions mymean and mymedian calculate the average and median of the input list. The main function mystats determines the length of the list n and passes it to the local functions.

Although you cannot call a local function from the command line or from functions in other files, you can access its help using the help function. Specify names of both the main function and the local function, separating them with a > character:help mystats>mymean mymean Example of a local function.

Page 14: The Language of Technical Computing

Local functions in the current file have precedence over functions in other files. That is, when you call a function within a program file, MATLAB checks whether the function is a local function before looking for other main functions. This allows you to create an alternate version of a particular function while retaining the original in another file.

All functions, including local functions, have their own workspaces that are separate from the base workspace. Local functions cannot access variables used by other functions unless you pass them as arguments. In contrast, nested functions (functions completely contained within another function) can access variables used by the functions that contain them.

Search MATLAB Documentation

R2012b

MATLAB

Programming Scripts and Functions

Functions

Function Basics

Nested Functions

On this page…

What Are Nested Functions?

Requirements for Nested Functions

Sharing Variables Between Parent and Nested Functions

Using Handles to Store Function Parameters

Visibility of Nested Functions

What Are Nested Functions?A nested function is a function that is completely contained within a parent function. Any function in a program file can include a nested function.

For example, this function named parent contains a nested function named nestedfx:function parentdisp('This is the parent function')nestedfx

function nestedfx

Page 15: The Language of Technical Computing

disp('This is the nested function') end

end

The primary difference between nested functions and other types of functions is that they can access and modify variables that are defined in their parent functions. As a result:

Nested functions can use variables that are not explicitly passed as input arguments.

In a parent function, you can create a handle to a nested function that contains the data necessary to run the nested function.

Requirements for Nested Functions Typically, functions do not require an end statement. However, to nest any

function in a program file, all functions in that file must use an end statement.

You cannot define a nested function inside any of the MATLAB program control statements, such as if/elseif/else, switch/case, for, while, or try/catch.

You must call a nested function either directly by name (without using feval), or using a function handle that you created using the @ operator (and not str2func).

All of the variables in nested functions or the functions that contain them must be explicitly defined. That is, you cannot call a function or script that assigns values to variables unless those variables already exist in the function workspace. (For more information, see Variables in Nested and Anonymous Functions.)

Sharing Variables Between Parent and Nested Functions

In general, variables in one function workspace are not available to other functions. However, nested functions can access and modify variables in the workspaces of the functions that contain them.

This means that both a nested function and a function that contains it can modify the same variable without passing that variable as an argument. For example, in each of these functions, main1 and main2, both the main function and the nested function can access variable x:function main1x = 5;nestfun1;

function nestfun1 x = x + 1; end

end

function main2nestfun2;

function nestfun2 x = 5; end x = x + 1;end

Page 16: The Language of Technical Computing

When parent functions do not use a given variable, the variable remains local to the nested function. For example, in this function named main, the two nested functions have their own versions of x that cannot interact with each other:function main nestedfun1; nestedfun2;

function nestedfun1 x = 1; end

function nestedfun2 x = 2; endend

Functions that return output arguments have variables for the outputs in their workspace. However, parent functions only have variables for the output of nested functions if they explicitly request them. For example, this function parentfun does not have variable y in its workspace:function parentfunx = 5;nestfun;

function y = nestfun y = x + 1; end

end

If you modify the code as follows, variable z is in the workspace of parentfun:function parentfunx = 5;z = nestfun;

function y = nestfun y = x + 1; end

end

Using Handles to Store Function Parameters

Nested functions can use variables from three sources:

Input arguments

Variables defined within the nested function

Variables defined in a parent function, also called externally scoped variables

When you create a function handle for a nested function, that handle stores not only the name of the function, but also the values of externally scoped variables.

Page 17: The Language of Technical Computing

For example, create a function in a file named makeParabola.m. This function accepts several polynomial coefficients, and returns a handle to a nested function that calculates the value of that polynomial.function p = makeParabola(a,b,c)p = @parabola;

function y = parabola(x) y = a*x.^2 + b*x + c; end

end

The makeParabola function returns a handle to the parabola function that includes values for coefficients a, b, and c.

At the command line, call the makeParabola function with coefficient values of 1.3, .2, and 30. Use the returned function handle p to evaluate the polynomial at a particular point:p = makeParabola(1.3,.2,30);

X = 25;Y = p(X)Y = 847.5000

Many MATLAB functions accept function handle inputs to evaluate functions over a range of values. For example, plot the parabolic equation from -25 to +25:fplot(p,[-25,25])

You can create multiple handles to the parabola function that each use different polynomial coefficients:firstp = makeParabola(0.8,1.6,32);secondp = makeParabola(3,4,50);range = [-25,25];

Page 18: The Language of Technical Computing

figurehold onfplot(firstp,range)fplot(secondp,range,'r:')hold off

Visibility of Nested FunctionsEvery function has a certain scope, that is, a set of other functions to which it is visible. A nested function is available:

From the level immediately above it. (In the following code, function A can call B or D, but not C or E.)

From a function nested at the same level within the same parent function. (Function B can call D, and D can call B.)

From a function at any lower level. (Function C can call B or D, but not E.)function A(x, y) % Main functionB(x,y);D(y);

function B(x,y) % Nested in A C(x); D(y);

function C(x) % Nested in B D(x); end end

function D(x) % Nested in A E(x);

function E(x) % Nested in D disp(x)

Page 19: The Language of Technical Computing

end endend

The easiest way to extend the scope of a nested function is to create a function handle and return it as an output argument, as shown in Using Handles to Store Function Parameters. Only functions that can call a nested function can create a handle to it.

Function Precedence Order

This topic explains how MATLAB determines which function to call when multiple functions in the current scope have the same name. The current scope includes the current file, an optional private subfolder relative to the currently running function, the current folder, and the MATLAB path.

MATLAB uses this precedence order:

1. Variables

Before assuming that a name matches a function, MATLAB checks for a variable with that name in the current workspace.

Note: If you create a variable with the same name as a function, MATLAB cannot run that function until you clear the variable from memory.

2. Nested functions within the current function

3. Local functions within the current file

4. Private functions

Private functions are functions in a subfolder named private that is immediately below the folder of the currently running file.

5. Overloaded methods

Overloading refers to intentionally reusing the same name. Overloaded methods typically implement similar functionality for different data types or classes. MATLAB checks the classes of the input arguments to determine which method to use.

6. Class constructors in @ folders

MATLAB uses class constructors to create a variety of objects (such as timeseries or audioplayer), and you can define your own classes using object-oriented programming. For example, if you create a class folder @polynom and a constructor function @polynom/polynom.m, the constructor takes precedence over other functions named polynom.m anywhere on the path.

7. Functions in the current folder

Page 20: The Language of Technical Computing

8. Functions elsewhere on the path, in order of appearance

When determining the precedence of functions within the same folder, MATLAB considers the file type, in this order:

1. Built-in function

2. MEX-function

3. Simulink® model, with file types in this order:

a. SLX file

b. MDL file

4. P-file (that is, an encoded program file with a .p extension)

5. Program file with a .m extension

For example, if MATLAB finds a .m file and a P-file with the same name in the same folder, it uses the P-file. Because P-files are not automatically regenerated, make sure that you regenerate the P-file whenever you edit the program file.

To determine the function MATLAB calls for a particular input, include the function name and the input in a call to the which function. For example, determine the location of the max method that MATLAB calls for double and int8 values:testval = 10;which max(testval)built-in (matlabroot\toolbox\matlab\datafun\@double\max) % double methodtestval = int8(10);which max(testval)built-in (matlabroot\toolbox\matlab\datafun\@int8\max) % int8 method

For more information, see:

What Is the Search Path?

Variables

Types of Functions

Overloading Functions for Your Class

Search MATLAB Documentation

R2012b

MATLAB

Page 21: The Language of Technical Computing

Language Fundamentals

Entering Commands

Variable Names

On this page…

Valid Names

Conflicts with Function Names

Valid NamesA valid variable name starts with a letter, followed by letters, digits, or underscores. MATLAB is case sensitive, so A and a are not the same variable. The maximum length of a variable name is the value that the namelengthmax command returns.

You cannot define variables with the same names as MATLAB keywords, such as if or end. For a complete list, run the iskeyword command.

Examples of valid names: Invalid names:

x6 6x

lastValue end

n_factorial n!

Conflicts with Function Names

Avoid creating variables with the same name as a function (such as i, j, mode, char, size, and path). In general, variable names take precedence over function names. If you create a variable that uses the name of a function, you sometimes get unexpected results.

Check whether a proposed name is already in use with the exist or which function. exist returns 0 if there are no existing variables, functions, or other artifacts with the proposed name. For example:exist checknameans = 0

If you inadvertently create a variable with a name conflict, remove the variable from memory with the clear function.

Another potential source of name conflicts occurs when you define a function that calls load or eval (or similar functions) to add variables to the workspace. In some cases,

Page 22: The Language of Technical Computing

load or eval add variables that have the same names as functions. Unless these variables are in the function workspace before the call to load or eval, the MATLAB parser interprets the variable names as function names. For more information, see:

Troubleshooting: Loading Variables within a Function

Alternatives to the eval Function

Search MATLAB Documentation

R2012b

MATLAB

Programming Scripts and Functions

Functions

Function Basics

Types of Functions

On this page…

Local and Nested Functions in a File

Private Functions in a Subfolder

Anonymous Functions Without a File

Local and Nested Functions in a FileProgram files can contain multiple functions: the main function and any combination of local or nested functions. Local and nested functions are useful for dividing programs into smaller tasks, making it easier to read and maintain your code.

Local functions are subroutines that are available to any other functions within the same file. They can appear in the file in any order after the main function in the file. Local functions are the most common way to break up programmatic tasks.

For example, create a single program file named myfunction.m that contains a main function, myfunction, and two local functions, squareMe and doubleMe:function b = myfunction(a) b = squareMe(a) + doubleMe(a);endfunction y = squareMe(x) y = x.^2;end

Page 23: The Language of Technical Computing

function y = doubleMe(x) y = x.*2;end

You can call the main function from the command line or another program file, although the local functions are only available to myfunction:myfunction(pi)ans = 16.1528

Nested functions are completely contained within another function. The primary difference between nested functions and local functions is that nested functions can use variables defined in parent functions without explicitly passing those variables as arguments.

Nested functions are useful when subroutines share data, such as GUI applications that pass data between components. For example, create a function that allows you to set a value between 0 and 1 using either a slider or an editable text box. If you use nested functions for the callbacks, the slider and text box can share the value and each other's handles without explicitly passing them:function myslidervalue = 0;f = figure;s = uicontrol(f,'Style','slider','Callback',@slider);e = uicontrol(f,'Style','edit','Callback',@edittext,... 'Position',[100,20,100,20]);

function slider(obj,~) value = get(obj,'Value'); set(e,'String',num2str(value)); end function edittext(obj,~) value = str2double(get(obj,'String')); set(s,'Value',value); end

end

For more information, see:

Local Functions

Nested Functions

Private Functions in a SubfolderLike local or nested functions, private functions are accessible only to functions in a specific location. However, private functions are not in the same file as the functions that can call them. Instead, they are in a subfolder named private. Private functions are available only to functions in the folder immediately above the private folder. Use private functions to separate code into different files, or to share code between multiple, related functions.

For more information, see Private Functions.

Page 24: The Language of Technical Computing

Anonymous Functions Without a FileAnonymous functions allow you to define a function without creating a program file, as long as the function consists of a single statement. A common application of anonymous functions is to define a mathematical expression, and then evaluate that expression over a range of values using a MATLAB function function—a function that accepts a function handle as an input.

For example, this statement creates a function handle named s for an anonymous function:s = @(x) sin(1./x);

This function has a single input, x. The @ operator creates the function handle.

You can use the function handle to evaluate the function for particular values, such asy = s(pi)y = 0.3130

Or, you can pass the function handle to a function that evaluates over a range of values, such as fplot:range = [0.01,0.1];fplot(s,range)

For more information, see Anonymous Functions.

http://www.mathworks.in/help/matlab/