User Tools

Site Tools


Matlab - language elements

As with any programming (or for-conversation) language, Matlab's core language has a few different types of elements that are worth understanding, as this will make it easier to read and write code that works and is robust as well as easy to understand and edit by others.

The very basic elements are:

  • comment sign (per-cent character, %): unless it appears as part of a string, everything else following this character til the end of the line is ignored by Matlab's language interpreter and meant as an explanatory help for the human reader
  • control flow keywords: these are reserved words that should not be used as part of user-defined expressions (although field names can be keywords, as they cannot be mistaken)
  • expressions: in principle, everything that Matlab “encounters” (on the command line as well as in a function or batch file) that is not a comment or a keyword is considered as an expression, which can be described as
    • a list of elements (with a minimum one element), whereas the different elements are described below, and elements using the same character set must be delimited by spaces, semicolon, or comma
    • a piece in a larger set of expressions (instruction list) whereas the order and selection of instructions is determined by the control flow keywords
    • a piece of code that makes Matlab perform internal computations (incl. user-defined function calls) and, possibly, stores a number of resulting outputs in variables (or clears/alters such variables)
  • line breaks: whenever the current line ends (or the return key is hit when using the command prompt), Matlab attempts to interpret (translate and act upon) the input language elements
  • space character: delimits elements in an expression (several spaces have the same effect as a single space)
  • semicolon (;): outside of expressions, the semicolon has two main functions, it separates individual statements (mostly useful when several short commands are grouped together) and suppresses the output of a command or statement (normally, if an expression leads to an output, the resulting value/s is/are stored in the default output variable, ans)
  • comma (,): also separates statements (if not used within a statement, that is), but does not suppress the output
  • ellipse (…): three consecutive dots work as a “line-continuation” character sequence, although this is no longer required in most instances (as Matlab detects an incomplete language construction), it may enhance readability of code

In addition, whenever Matlab encounters a word (sequence of alphanumeric characters beginning with a letter) that is not part of a string, a keyword, or addressing a fieldname of a structure (such as in structure.FieldName), Matlab tries to “resolve” (understand) this word in the following precedence (lookup, see function precedence order page on Mathworks):

  • variables (names referenced in the current workspace)
  • nested functions
  • locally defined function (in the same scope/function file)
  • private functions (functions defined in any folder called “private” existing in the folder of the currently running file)
  • if an argument is an object, a class method (of the corresponding class, in order of arguments, which is the way to overload built-in functions)
  • built-in functions
  • class-constructor functions (@class/class.m)
  • function names (in order of path precedence, within folder precedence is MEX, P-file, M-file)

This means that functions (built-in as well as user defined) can always be overridden by variables and appropriate class methods (e.g. for the @double class), which offers great opportunities, but also potential hazards. Also, functions that are part of Matlab's internal toolboxes but not fully built-in (e.g. var) can be overridden by user-defined functions. That means that you should be careful not to re-use function names that are already defined when writing your own functions!


This language element is mostly useful when code is not entered into the command line but rather organized in text files for repeated processing of statements.

% this is a comment describing the next statement line
disp('this is the first statement, displaying a line');
% this is another comment, describing that two numbers are added
s = a + b;

Control flow elements

When writing code, it is often crucial to be able to

  • define new functions that provide access to repeatedly used code
  • execute certain expressions only conditionally (if and only if a condition is met or not met)
  • execute an expression or list of expressions repeatedly (either for a predetermined number of iterations or until an exit criterion is met)
  • select a (list of) expression/s based on another expression (value)
  • be able to react to an error that occurred as part of a statement without leaving the code
  • return from a function prematurely (e.g. in case nothing else can be done that makes sense)

Defining new functions

As explained above, Matlab interprets any word it encounters as potentially belonging to a function. To define a new function, all that is needed is to create a new file and add the desired function declaration on top (first line of actual code after optional comments):

function [list_of_outputs] = function_name(list_of_inputs)
% further optional comments
list_of_outputs = some_code(list_of_inputs);

The list_of_outputs and list_of_inputs words (identifiers) are optional, depending on the desired functionality. Sometimes, a function is not required to return any useful value (e.g. a function instructing Matlab to wait until a desired point in time is reached), or it requires no input (e.g. a function used to determine the currently active figure). However, in most situations (particularly where computations are performed), user defined functions will have both inputs (variables passed into the function such that the function has access to the values stored therein) and outputs (variables that, once the function has completed executing, will be passed back to the code that called the function).

As an additional language construct (which can be considered as pseudo-reserved keywords), the two identifiers varargin and varargout can be used to pass a variable number of arguments into a function and also allow the function to return a number of variables that is determined at run-time:

function [varargout] = variable_arguments_function(varargin)
% storing the sum of the first two arguments in the third output
varargout{3} = varargin{1} + varargin{2};

To make such code reliable, it is usually advisable to test the number of given inputs as well as the number of requested outputs with the corresponding nargin and nargout variables which are always pre-assigned before a function is executed.

One last important fact about functions: While Matlab does not create a copy of the variables before they are passed into a function, Matlab will not alter the content of a variable as it exists within the workspace that calls the function. In other words, if the following function is called:

function x = add1tox(x)
% add 1 to input
x = x + 1;

in the following way:

% define a variable
somevar = 10;
% call add1tox

The variable somevar will still have the value of 10! This is true regardless of the type or size of the variable (unless the storage is only referenced by the variable, such as for graphics handles or user defined objects)!

Conditional code execution

Matlab's principle way of allowing to execute code based on a conditional statement looks as follows:

% open a control flow structure, giving a condition
% upon which the embedded expressions are executed
if my_condition_is_met

The conditional expression that is given immediately following the if keyword is executed (and is, in fact, nothing but another expression). It usually is expected that this conditional expression returns a boolean (true or false) value, such that Matlab will then either execute the embedded expressions (if the conditional statement evaluates to true) or not (false). In case the conditional statement does not return a boolean value, Matlab automatically converts the returned value (if possible). In case this conversion fails, an error is thrown.

Conditional expressions can be “linked” (several conditions can be evaluated), by using logic operators (double ampersand and pipe characters):

if (test1 && test2) || (test3 && test4)

Which means that if either both test1 and test2 (these two) or both test3 and test4 result in a true outcome, some_function will be called with the input argument of some_value.

matlab_-_language.txt · Last modified: 2012/11/12 22:02 by jochen