What am I doing wrong in MATLAB

Select a web site

Scripts and functions


MATLAB® provides a powerful programming language and an interactive computer environment. You can enter commands of the language one at a time on the MATLAB command line, or you can write a series of commands to a file, which you then execute like any other MATLAB function. Use MATLAB Editor or any other text editor to create your own function files. Call these functions like any other MATLAB function or command.

There are two types of program files:

  • Scripts that do not accept input arguments or return no output arguments. These are applied to the data in the work area.

  • Functions that take input arguments and return output arguments. Internal variables are available locally for the function.

If you are new to programming in MATLAB, simply create the program files you want to try out in the current folder. As you develop a large number of your own files over time, you will organize them in other folders and personal toolboxes that you can add to your MATLAB search path.

If you duplicate function names, MATLAB executes the function with the first occurrence in the search path.

For example, if you want to view the contents of a program file, type:


If you have a script call, MATLAB simplifies the commands found in the file. Scripts can be applied to existing data in the workspace, or they can create new data to be applied to. Even if scripts do not return any output arguments, any variables they create remain in the work area so they can be used in subsequent calculations. You can also create scripts using functions such as graphical output.

For example, create a file named that contains the following MATLAB commands:

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

If you follow the instruction

input, MATLAB executes the commands, calculates the rank of the first 30 magic squares, and plots a bar graph of the result. When the file is executed, the variables and remain in the work area.


Functions are files that accept input arguments and return output arguments. The names of the file and the function must be identical. Functions are applied to variables within their own work area, i.e. separate from the work area accessed through the MATLAB prompt.

A good example is the function. You can find the file in the folder

To view the file, enter:

The content of the file looks like this:

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 begins with the keyword. It specifies the function name and the order of the arguments. In this case there are up to two input arguments and one output argument.

The next lines - up to the first empty or executable line - are comment lines with the help text. These lines are printed when you type:

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

The remainder of the file is the executable MATLAB program code that defines the function. The variables in the function body and the variables from the first line,, and, are local Function variables. They are separate from the variables in the MATLAB workspace.

This example illustrates one aspect of MATLAB functions that other programming languages ​​normally do not offer: a variable number of arguments. The function can be used in many different ways:

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

Many functions work this way. If no output argument is given, the result is stored in. If the second input argument is omitted, the function calculates a default value. Within the function body, there are two variables with the names and available that specify how many input and output arguments are involved in using the function. The function uses, but does not have to use.

Function types

MATLAB provides various types of functions that can be used for programming.

Anonymous functions

A anonymous function is a simple form of the MATLAB function that is defined with 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 directly on the MATLAB command line or within a function or script. In this way, simple functions can be created quickly without having to create a file for the respective function each time.

The syntax for creating an anonymous function from an expression is as follows:

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

Enter the following to run the function:

Main functions and local functions

All functions that are not anonymous must be defined in a file. Each of these function files contains a required Main functionthat appears first and any number local functionsthat can follow the main function. Main functions have a wider area of ​​application than local functions. This means that main functions can be called outside of the file in which they are defined (for example from the MATLAB command line or from functions in other files), while this is not possible for local functions. Local functions are only visible to the main function and the other local functions within their own file.

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

Private functions

A private function is a type of main function. Its unique selling point is that it is only visible to a limited group of other functions. This type of function can be useful when you want to limit access to a function or when you want to make the implementations of a function unavailable.

Private functions are located in sub-folders with the special name. They are only visible for functions in the higher-level folder. For example, suppose the folder is in MATLAB's search path. A subfolder with the name can contain functions that can only be called by functions in.

Since private functions are not visible outside the parent folder, they can use the same names as functions in other folders. This is useful when you want to use your own version of a particular function while keeping the original in a different folder. Since MATLAB searches for private functions first and then for standard functions, a private function with the name is found before a non-private file with the name.

Nested functions

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

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

Just like other functions, a nested function has its own work area that stores the variables used by the function. However, it also has access to the workspaces of all functions in which it is nested. For example, a variable that has been assigned a value by the main function can be read or overwritten by a function that is nested at any level with the main function. Similarly, a variable assigned in a nested function can be read or overwritten by any of the functions that contain that function.

global variables

If you want multiple functions to share a single copy of a variable, simply declare the variable as a. Set the same thing on the command line if you want the base workspace to be able to access the variable. The global declaration must exist before the variable is actually used in a function. Although not required, you can use capital letters for the names of global variables to help distinguish them from the other variables. For example, create a new function in a file named:

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

Then enter the following instructions interactively:

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

The two global statements make the value assigned in the command line available within the function. You can then make changes interactively and receive new solutions without having to edit files.

Command vs. function syntax

You can write MATLAB functions that take character arguments without the parentheses and quotation marks. That means MATLAB

interpreted as follows:

So if you use the command form without the quotation marks, MATLAB cannot return any output arguments. For example, created

a legend in a plot using the labels and. If you want the command to return its output arguments, you must use the command form with quotation marks:

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

Also, you must use the quotes form if any of the arguments is not a character vector.


While the command syntax without the quotation marks is convenient, in some cases it can be misused without MATLAB generating an error.

Constructing character arguments in code

The function form with quotation marks allows you to construct character arguments within the code. The following example processes multiple data files:, etc. It uses the function that converts an integer to a character to create 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