• Home   /  
  • Archive by category "1"

Matlab Function Example Simple Essay

declares a function named that accepts inputs and returns outputs . This declaration statement must be the first executable line of the function. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

You can save your function:

  • In a function file which contains only function definitions. The name of the file should match the name of the first function in the file.

  • In a script file which contains commands and function definitions. Functions must be at the end of the file. Script files cannot have the same name as a function in the file. Functions are supported in scripts in R2016b or later.

Files can include multiple local functions or nested functions. For readability, use the keyword to indicate the end of each function in a file. The keyword is required when:

  • Any function in the file contains a nested function.

  • The function is a local function within a function file, and any local function in the file uses the keyword.

  • The function is a local function within a script file.

Scripts and Functions


The MATLAB® product provides a powerful programming language, as well as an interactive computational environment. You can enter commands from the language one at a time at the MATLAB command line, or you can write a series of commands to a file that you then execute as you would any MATLAB function. Use the MATLAB Editor or any other text editor to create your own function files. Call these functions as you would any other MATLAB function or command.

There are two kinds of program files:

  • Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.

  • Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.

If you are a new MATLAB programmer, just create the program files that you want to try out in the current folder. As you develop more of your own files, you will want to organize them into other folders and personal toolboxes that you can add to your MATLAB search path.

If you duplicate function names, MATLAB executes the one that occurs first in the search path.

To view the contents of a program file, for example, , use


When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like .

For example, create a file called that contains these MATLAB commands:

% Investigate the rank of magic squares r = zeros(1,32); for n = 3:32 r(n) = rank(magic(n)); end r bar(r)

Typing the statement

causes MATLAB to execute the commands, compute the rank of the first 30 magic squares, and plot a bar graph of the result. After execution of the file is complete, the variables and remain in the workspace.


Functions are files that can accept input arguments and return output arguments. The names of the file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.

A good example is provided by . The file is available in the folder

You can see the file with

Here is the file:

function r = rank(A,tol) % RANK Matrix rank. % RANK(A) provides an estimate of the number of linearly % independent rows or columns of a matrix A. % RANK(A,tol) is the number of singular values of A % that are larger than tol. % RANK(A) uses the default tol = max(size(A)) * norm(A) * eps. s = svd(A); if nargin==1 tol = max(size(A)') * max(s) * eps; end r = sum(s > tol);

The first line of a function starts with the keyword . It gives the function name and order of arguments. In this case, there are up to two input arguments and one output argument.

The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines are printed when you type

The first line of the help text is the H1 line, which MATLAB displays when you use the command or request on a folder.

The rest of the file is the executable MATLAB code defining the function. The variable introduced in the body of the function, as well as the variables on the first line, , and , are all local to the function; they are separate from any variables in the MATLAB workspace.

This example illustrates one aspect of MATLAB functions that is not ordinarily found in other programming languages—a variable number of arguments. The function can be used in several different ways:

rank(A) r = rank(A) r = rank(A,1.e-6)

Many functions work this way. If no output argument is supplied, the result is stored in . If the second input argument is not supplied, the function computes a default value. Within the body of the function, two quantities named and are available that tell you the number of input and output arguments involved in each particular use of the function. The function uses , but does not need to use .

Types of Functions

MATLAB offers several different types of functions to use in your programming.

Anonymous Functions

An anonymous function is a simple form of the MATLAB function that is defined within a single MATLAB statement. It consists of a single MATLAB expression and any number of input and output arguments. You can define an anonymous function right at the MATLAB command line, or within a function or script. This gives you a quick means of creating simple functions without having to create a file for them each time.

The syntax for creating an anonymous function from an expression is

The statement below creates an anonymous function that finds the square of a number. When you call this function, MATLAB assigns the value you pass in to variable , and then uses in the equation :

To execute the function defined above, type

Primary and Subfunctions

Any function that is not anonymous must be defined within a file. Each such function file contains a required primary function that appears first, and any number of subfunctions that can follow the primary. Primary functions have a wider scope than subfunctions. That is, primary functions can be called from outside of the file that defines them (for example, from the MATLAB command line or from functions in other files) while subfunctions cannot. Subfunctions are visible only to the primary function and other subfunctions within their own file.

The function shown in the section on Functions is an example of a primary function.

Private Functions

A private function is a type of primary function. Its unique characteristic is that it is visible only to a limited group of other functions. This type of function can be useful if you want to limit access to a function, or when you choose not to expose the implementation of a function.

Private functions reside in subfolders with the special name . They are visible only to functions in the parent folder. For example, assume the folder is on the MATLAB search path. A subfolder of called can contain functions that only the functions in can call.

Because private functions are invisible outside the parent folder, they can use the same names as functions in other folders. This is useful if you want to create your own version of a particular function while retaining the original in another folder. Because MATLAB looks for private functions before standard functions, it will find a private function named before a nonprivate file named .

Nested Functions

You can define functions within the body of another function. These are said to be nested within the outer function. A nested function contains any or all of the components of any other function. In this example, function is nested in function :

function x = A(p1, p2) ... B(p2) function y = B(p3) ... end ... end

Like other functions, a nested function has its own workspace where variables used by the function are stored. But it also has access to the workspaces of all functions in which it is nested. So, for example, a variable that has a value assigned to it by the primary function can be read or overwritten by a function nested at any level within the primary. Similarly, a variable that is assigned in a nested function can be read or overwritten by any of the functions containing that function.

Global Variables

If you want more than one function to share a single copy of a variable, simply declare the variable as in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function. Although it is not required, using capital letters for the names of global variables helps distinguish them from other variables. For example, create a new function in a file called :

function h = falling(t) global GRAVITY h = 1/2*GRAVITY*t.^2;

Then interactively enter the statements

global GRAVITY GRAVITY = 32; y = falling((0:.1:5)');

The two global statements make the value assigned to at the command prompt available inside the function. You can then modify interactively and obtain new solutions without editing any files.

Command vs. Function Syntax

You can write MATLAB functions that accept character arguments without the parentheses and quotes. That is, MATLAB interprets


However, when you use the unquoted command form, MATLAB cannot return output arguments. For example,

creates a legend on a plot using and as labels. If you want the command to return its output arguments, then you must use the quoted form:

[legh,objh] = legend('apples','oranges');

In addition, you must use the quoted form if any of the arguments is not a character vector.


While the unquoted command syntax is convenient, in some cases it can be used incorrectly without causing MATLAB to generate an error.

Constructing Character Arguments in Code

The quoted function form enables you to construct character arguments within the code. The following example processes multiple data files, , , and so on. It uses the function , which converts an integer to a character, to build the file name:

for d = 1:31 s = ['August' int2str(d) '.dat']; load(s) % Code to process the contents of the d-th file end

One thought on “Matlab Function Example Simple Essay

Leave a comment

L'indirizzo email non verrĂ  pubblicato. I campi obbligatori sono contrassegnati *