This section describes functions related to programming: function arguments, error processing, evaluation, memory.
Check that an assertion is true.
assert(expr) assert(expr, str) assert(expr, format, arg1, arg2, ...) assert(expr, identifier, format, arg1, arg2, ...)
assert(expr) checks that expr is true and throws an error otherwise. Expression expr is considered to be true if it is a non-empty array whose elements are all non-zero.
With more input arguments, assert checks that expr is true and throws the error specified by remaining arguments otherwise. These arguments are the same as those expected by function error.
When the intermediate code is optimized, assert can be ignored. It should be used only to produce errors at an early stage or as a debugging aid, not to trigger the try/catch mechanism. The expression should not have side effects. The most common use of assert is to check the validity of input arguments.
function y = fact(n) assert(length(n)==1 && isreal(n) && n==round(n), 'LME:nonIntArg'); y = prod(1:n);
Built-in function evaluation.
(argout1, ...) = builtin(fun, argin1, ...)
(y1,y2,...)=builtin(fun,x1,x2,...) evaluates the built-in function fun with input arguments x1, x2, etc. Output arguments are assigned to y1, y2, etc. Function fun is specified by its name as a string.
builtin is useful to execute a built-in function which has been redefined.
Here is the definition of operator plus so that it can be used with character strings to concatenate them.
function r = plus(a, b) if ischar(a) && ischar(b) r = [a, b]; else r = builtin('plus', a, b); end
The original meaning of plus for numbers is preserved:
1 + 2 3 'ab' + 'cdef' abcdef
Discard the contents of a variable.
clear clear(v1, v2, ...) clear -functions
Without argument, clear discards the contents of all the local variables, including input arguments. With string input arguments, clear(v1,v2,...) discards the contents of the enumerated variables. Note that the variables are specified by strings; clear is a normal function which evaluates its arguments if they are enclosed between parenthesis. You can also omit parenthesis and quotes and use command syntax.
clear is usually not necessary, because local variables are automatically discarded when the function returns. It may be useful if a large variable is used only at the beginning of a function, or at the command-line interface.
clear -functions or clear -f removes the definition of all functions. It can be used only from the command-line interface, not in a function.
In the example below, clear(b) evaluates its argument and clears the variable whose name is 'a'; clear b, without parenthesis and quotes, does not evaluate it; the argument is the literal string 'b'.
a = 2; b = 'a'; clear(b) a Undefined variable 'a' b a clear b b Undefined variable b
Copy input arguments to output arguments.
(v1, v2, ...) = deal(e) (v1, v2, ...) = deal(e1, e2, ...)
With a single input argument, deal provides a copy of it to all its output arguments. With multiple input arguments, deal provides them as output arguments in the same order.
deal can be used to assign a value to multiple variables, to swap the contents of two variables, or to assign the elements of a list to different variables.
Swap variable a and b:
a = 2; b = 'abc'; (a, b) = deal(b, a) a = abc b = 2
Copy the same random matrix to variables x, y, and z:
(x, y, z) = deal(rand(5));
Assign the elements of list l to variables v1, v2, and v3:
l = {1, 'abc', 3:5}; (v1, v2, v3) = deal(l{:}) v1 = 1 v2 = abc v3 = 3 4 5
varargin, varargout, operator {}
Dump the value of an expression as an assignment to a variable.
dumpvar(value) dumpvar(name,value) dumpvar(fd,name,value) str = dumpvar(value) str = dumpvar(name,value)
dumpvar(fd,name,value) writes to the channel fd (the standard output by default) a string which would set the variable name to value, if it was evaluated by LME. If name is omitted, only the textual representation of value is written.
With an output argument, dumpvar stores result into a string and produces no output.
dumpvar(2+3) 5 a = 6; dumpvar('a', a) a = 6; s = 'abc'; dumpvar('string', s) string = 'abc';
Display an error message and abort the current computation.
error(str) error(format, arg1, arg2, ...) error(identifier, format, arg1, arg2, ...)
Outside a try block, error(str) displays string str as an error message and the computation is aborted. With more arguments, error use the first argument as a format string and displays remaining arguments accordingly, like fprintf.
In a try block, error(str) throws a user error without displaying anything.
An error identifier may be added in front of other arguments. It is a string made of at least two segments separated by semicolons. Each segment has the same syntax as variable or function name (i.e. it begins with a letter or an underscore, and it continues with letters, digits and underscores.) The identifier can be retrieved with lasterr or lasterror in the catch part of a try/catch construct and helps to identify the error. For errors thrown by LME built-in functions, the first segment is always LME.
error('Invalid argument.'); Invalid argument. o = 'ground'; error('robot:hit', 'The robot is going to hit %s', o); The robot is going to hit ground lasterror message: 'The robot is going to hit ground' identifier: 'robot:hit'
warning, try, lasterr, lasterror, assert, fprintf
Evaluate the contents of a string as an expression or statements.
x = eval(str_expression) eval(str_statement)
If eval has output argument(s), the input argument is evaluated as an expression whose result(s) is returned. Without output arguments, the input argument is evaluated as statement(s). eval can evaluate and assign to existing variables, but cannot create new ones.
eval('1+2') 3 a = eval('1+2') a = 3 eval('a=2+3') a = 5
Existence of a function or variable.
b = exist(name) b = exist(name, type)
exist returns true if its argument is the name of an existing function or variable, or false otherwise. A second argument can restrict the lookup to builtin functions ('builtin'), user functions ('function'), or variable ('variable').
exist('sin') true exist('cos', 'function') false
Function evaluation.
(argout1,...) = feval(fun,argin1,...)
(y1,y2,...)=feval(fun,x1,x2,...) evaluates function fun with input arguments x1, x2, etc. Output arguments are assigned to y1, y2, etc. Function fun is specified by either its name as a string, a function reference, or an inline function.
y = feval('sin', 3:5) y = 0.1411 -0.7568 -0.9589 y = feval(inline('sin(2*x)'), 3:5) y = -0.2794 0.9894 -0.544
builtin, eval, fevalx, apply, inline, operator @
Function evaluation with array expansion.
(Y1,...) = fevalx(fun,X1,...)
(Y1,Y2,...)=fevalx(fun,X1,X2,...) evaluates function fun with input arguments X1, X2, etc. Arguments must be arrays, which are expanded if necessary along singleton dimensions so that all dimensions match. For instance, three arguments of size 3x1x2, 1x5 and 1x1 are replicated into arrays of size 3x5x2. Output arguments are assigned to Y1, Y2, etc. Function fun is specified by either by its name as a string, a function reference, or an inline function.
fevalx(@plus, 1:5, (10:10:30)') 11 12 13 14 15 21 22 23 24 25 31 32 33 34 35
feval, meshgrid, repmat, inline, operator @
Name of a function given by reference or source code of an inline function.
str = fun2str(funref) str = fun2str(inlinefun)
fun2str(funref) gives the name of the function whose reference is funref.
fun2str(inlinefun) gives the source code of the inline function inlinefun.
fun2str(@sin) sin fun2str(inline('x+2*y', 'x', 'y')) function y=f(x,y);y=x+2*y;
Information about LME.
info info builtin info functions info methods info variables info global info persistent info libraries info usedlibraries info threads str = info list = info(kind)
info displays the language version. With an output argument, the language version is given as a string.
info builtin displays the list of built-in functions with their module name (modules are subsets of built-in functions). A letter u is displayed after each untrusted function (functions which cannot be executed in the sandbox). With an output argument, info('builtin') gives a list of structures which describe each built-in function, with the following fields:
name | function name |
module | module name |
trusted | true if the function is trusted |
info operators displays the list of operators. With an output argument, info('operators') gives a list of structures, like info('builtin').
info functions displays the list of user-defined functions with the library where they are defined. Parenthesis denote functions known by LME, but not loaded; they also indicate spelling errors in function or variable names. With an output argument, info('functions') gives a list of structures which describe each user-defined function, with the following fields:
library | library name |
name | function name |
loaded | true if loaded |
info methods displays the list of methods. With an output argument, info('methods') gives a list of structures which describe each method, with the following fields:
library | library name |
class | class name |
name | function name |
loaded | true if loaded |
info variables displays the list of variables with their type and size. With an output argument, info('methods') gives a list of structures which describe each variable, with the following fields:
name | function name |
defined | true if defined |
info global displays the list of all global variables. With an output argument, info('global') gives the list of the global variable names.
info persistent displays the list of all persistent variables. With an output argument, info('persistent') gives the list of the persistent variable names.
info libraries displays the list of all loaded libraries. With an output argument, info('libraries') gives the list of the library names.
info usedlibraries displays the list of libraries available in the current context. With an output argument, info('usedlibraries') gives the list of the names of these libraries.
info threads displays the ID of all threads. With an output argument, info('threads') gives a list of structures which describe each thread, with the following fields:
id | thread ID |
totaltime | execution time in seconds |
Only the first character of the argument is meaningful; info b is equivalent to info builtin.
info LME 4.5 info b abs acos acosh (etc.) info v ans (1x1 complex) vars = info('v'); dumpvar(vars) {struct('name','ans', ... 'defined',true), ... struct('name','vars', ... 'defined',false)}
Creation of inline function.
fun = inline(funstr) fun = inline(expr) fun = inline(expr, arg1, ...) fun = inline(funstr, param) fun = inline(expr, arg1, ..., paramstruct)
Inline function are LME objects which can be evaluated to give a result as a function of their input arguments. Contrary to functions declared with the function keyword, inline functions can be assigned to variables, passed as arguments, and built dynamically. Evaluating them with feval is faster than using eval with a string, because they are compiled only once to an intermediate code. They can also be used as the argument of functions such as fzero and fmin.
inline(funstr) returns an inline function whose source code is funstr. Input argument funstr follows the same syntax as a plain function. The function name is ignored.
inline(expr) returns an inline function with one implicit input argument and one result. The input argument expr is a string which evaluates to the result. The implicit input argument of the inline function is a symbol made of a single lower-case letter different from i and j, such as x or t, which is found in expr. If several such symbols are found, the one closer to x in alphabetical order is picked.
inline(expr,arg1,...) returns an inline function with one result and the specified arguments arg1 etc. These arguments are also given as strings.
Inline functions also accept an additional input argument which correspond to fixed parameters provided when the function is executed. inline(funstr,param), where funstr is a string which contains the source code of a function, stores param together with the function. When the function is called, param is prepended to the list of input arguments.
inline(expr,args,paramstruct) is a simplified way to create an inline function when the code consists of a single expression. args is the list of arguments which must be supplied when the inline function is called; paramstruct is a structure whose fields define fixed parameters.
Anonymous functions are an alternative, often easier way of creating inline functions. The result is the same. Since inline is a normal function, it must be used in contexts where fixed parameters cannot be created as separate variables.
A simple expression, evaluated at x=1 and x=2:
fun = inline('cos(x)*exp(-x)'); y = feval(fun, 2) y = -5.6319e-2 y = feval(fun, 5) y = 1.9113e-3
A function of x and y:
fun = inline('exp(-x^2-y^2)', 'x', 'y');
A function with two output arguments (the string is broken in three lines to have a nice program layout):
fun = inline(['function (a,b)=f(v);',... 'a=mean(v);',... 'b=prod(v)^(1/length(v));']); (am, gm) = feval(fun, 1:10) am = 5.5 gm = 4.5287
Simple expression with fixed parameter a:
fun = inline('cos(a*x)', 'x', struct('a',2)); feval(fun, 3) 0.9602
An equivalent function where the source code of a complete function is provided:
fun = inline('function y=f(a,x); y=cos(a*x);', 2); feval(fun, 3) 0.9602
A function with two fixed parameters a and b whose values are provided in a list:
inline('function y=f(p,x);(a,b)=deal(p{:});y=a*x+b;',{2,3})
function, operator @, feval, eval
List of functions loaded in memory.
inmem list = inmem
inmem displays the list of user-defined functions loaded in memory with the library where they are defined. With an output argument, inmem gives a list of structures which describe each user-defined function loaded in memory, with the following fields:
library | library name |
class | class name ('' for functions) |
name | function name |
Test for the existence of a global variable.
b = isglobal(str)
isglobal(str) returns true if the string str is the name of a global variable, defined as such in the current context.
Test for a keyword name.
b = iskeyword(str) list = iskeyword
iskeyword(str) returns true if the string str is a reserved keyword which cannot be used as a function or variable name, or false otherwise. Keywords include if and global, but not the name of built-in functions like sin or i.
Without input argument, iskeyword gives the list of all keywords.
iskeyword('otherwise') true iskeyword {'break','case','catch','continue','else','elseif', 'end','endfunction','for','function','global','if', 'otherwise','persistent','private','public','repeat', 'return','switch','try','until','use','useifexists', 'while'}
Last error message.
msg = lasterr (msg, identifier) = lasterr
lasterr returns a string which describes the last error. With two output arguments, it also gives the error identifier. It can be used in the catch part of the try construct.
x = 2; x(3) Index out of range (msg, identifier) = lasterr msg = Index out of range identifier = LME:indexOutOfRange
Last error structure.
s = lasterror
lasterror returns a structure which describes the last error. It contains the following fields:
identifier | string | short tag which identifies the error |
message | string | error message |
The structure can be used as argument to rethrow in the catch part of a try/catch construct to propagate the error further.
x = 2; x(3) Index out of range lasterror message: 'Index out of range' identifier: 'LME:indexOutOfRange'
Number of input arguments.
n = nargin n = nargin(fun)
Calling a function with less arguments than what the function expects is permitted. In this case, the trailing variables are not defined. The function may use the nargin function to know how many arguments were passed by the caller to avoid accessing the undefined variables.
Note that if you want to have an optional argument before the end of the list, you have to interpret the meaning of the variables yourself. LME always sets the nargin first arguments.
There are two other ways to let a function accept a variable number of input arguments: to define default values directly in the function header, or to call varargin to collect some or all of the input arguments in a list.
With one argument, nargin(fun) returns the (maximum) number of input arguments a function accepts. fun may be the name of a built-in or user function, a function reference, or an inline function. Functions with a variable number of input arguments (such as fprintf) give -1.
A function with a default value (pi) for its second argument:
function x = multiplyByScalar(a,k) if nargin < 2 % multiplyByScalar(x) k = pi; % same as multiplyByScalar(x,pi) end x = k * a;
A function with a default value (standard output) for its first argument. Note how you have to interpret the arguments.
function fprintstars(fd,n) if nargin == 1 % fprintstars(n) to standard output fprintf(repmat('*',1,fd)); % n is actually stored in fd else fprintf(fd, repmat('*',1,n)); end
Number of input arguments of function plus (usually written "+"):
nargin('plus') 2
Number of output arguments.
n = nargout n = nargout(fun)
A function may be called with between 0 and the number of output arguments listed in the function definition. The function can use nargout to check whether some output arguments are not used, so that it can avoid computing them or do something else.
With one argument, nargout(fun) returns the (maximum) number of output arguments a function can provide. fun may be the name of a built-in or user function, a function reference, or an inline function. Functions with a variable number of output arguments (such as feval) give -1.
A function which prints nicely its result when it is not assigned or used in an expression:
function y = multiplyByTwo(x) if nargout > 0 y = 2 * x; else fprintf('The double of %f is %f\n', x, 2*x); end
Maximum number of output arguments of svd:
nargout('svd') 3
Throw an error described by a structure.
rethrow(s)
rethrow(s) throws an error described by structure s, which contains the same fields as the output of lasterror. rethrow is typically used in the catch part of a try/catch construct to propagate further an error; but it can also be used to initiate an error, like error.
The error whose identifier is 'LME:indexOutOfRange' is handled by catch; other errors are not.
try ... catch err = lasterror; if err.identifier === 'LME:indexOutOfRange' ... else rethrow(err); end end
Function reference.
funref = str2fun(str)
str2fun(funref) gives a function reference to the function whose name is given in string str. It has the same effect as operator @, which is preferred when the function name is fixed.
str2fun('sin') @sin @sin @sin a = 'cos'; str2fun(a) @cos
Convert to an object its string representation.
obj = str2obj(str)
str2obj(str) evaluates string str and gives its result. It has the inverse effect as dumpvar with one argument. It differs from eval by restricting the syntax it accepts to literal values and to the basic constructs for creating complex numbers, arrays, lists, structures, objects, and other built-in types.
str2obj('1+2j') 1 + 2j str = dumpvar({1, 'abc', 1:100}) str = {1, ... 'abc', ... [1:100]} str2obj(str) {1,'abc',real 1x100} eval(str) {1,'abc',real 1x100} str2obj('sin(2)') Bad argument 'str2obj' eval('sin(2)') 0.9093
Remaining input arguments.
function ... = fun(..., varargin) l = varargin
varargin is a special variable which may be used to collect input arguments. In the function declaration, it must be used as the last (or unique) input argument. When the function is called with more arguments than what can be assigned to the other arguments, remaining ones are collected in a list and assigned to varargin. In the body of the function, varargin is a normal variable. Its elements may be accessed with the brace notation varargin{i}. nargin is always the total number of arguments passed to the function by the caller.
When the function is called with fewer arguments than what is declared, varargin is set to the empty list, {}.
Here is a function which accepts any number of square matrices and builds a block-diagonal matrix:
function M = blockdiag(varargin) M = []; for block = varargin // block takes the value of each input argument (m, n) = size(block); M(end+1:end+m,end+1:end+n) = block; end
In the call below, varargin contains the list {ones(3),2*ones(2),3}.
blockdiag(ones(3),2*ones(2),3) 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 2 2 0 0 0 0 2 2 0 0 0 0 0 0 3
Remaining output arguments.
function (..., varargout) = fun(...) varargout = ...
varargout is a special variable which may be used to dispatch output arguments. In the function declaration, it must be used as the last (or unique) output argument. When the function is called with more output arguments than what can be obtained from the other arguments, remaining ones are extracted from the list varargout. In the body of the function, varargout is a normal variable. Its value can be set globally with the brace notation {...} or element by element with varargout{i}. nargout may be used to know how many output arguments to produce.
Here is a function which differentiates a vector of values as many times as there are output arguments:
function varargout = multidiff(v) for i = 1:nargout v = diff(v); varargout{i} = v; end
In the call below, [1,3,7,2,5,3,1,8] is differentiated four times.
(v1, v2, v3, v4) = multidiff([1,3,7,2,5,3,1,8]) v1 = 2 4 -5 3 -2 -2 7 v2 = 2 -9 8 -5 0 9 v3 = -11 17 -13 5 9 v4 = 28 -30 18 4
Contents of the variables as a structure.
v = variables
variables returns a structure whose fields contain the variables defined in the current context.
a = 3; b = 1:5; variables a: 3 b: real 1x5 ...
Write a warning to the standard error channel.
warning(msg) warning(format, arg1, arg2, ...)
warning(msg) displays the string msg. It should be used to notify the user about potential problems, not as a general-purpose display function.
With more arguments, warning uses the first argument as a format string and displays remaining arguments accordingly, like fprintf.
warning('Doesn\'t converge.');
Library where a function is defined.
fullname = which(name)
which(name) returns an indication of where function name is defined. If name is a user function or a method prefixed with its class and two colons, the result is name prefixed with the library name and a slash. If name is a built-in function, it is prefixed with (builtin). If it is a variable, it is prefixed with (var). If name is neither a function nor a variable, which returns the empty string.
which logspace stdlib/logspace which polynom::plus classes/polynom::plus which sin (builtin)/sin x = 2; which x (var)/x