en fr

Sysquake Pro – Table of Contents

Sysquake – Table of Contents

Sysquake for LaTeX – Table of Contents

Programming Functions

This section describes functions related to programming: function arguments, error processing, evaluation, memory.

assert

Check that an assertion is true.

Syntax

assert(expr)
assert(expr, str)
assert(expr, format, arg1, arg2, ...)
assert(expr, identifier, format, arg1, arg2, ...)

Description

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.

Example

function y = fact(n)
  assert(length(n)==1 && isreal(n) && n==round(n), 'LME:nonIntArg');
  y = prod(1:n);

See also

error, warning, try

builtin

Built-in function evaluation.

Syntax

(argout1, ...) = builtin(fun, argin1, ...)

Description

(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.

Example

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

See also

feval

clear

Discard the contents of a variable.

Syntax

clear
clear(v1, v2, ...)
clear -functions

Description

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.

Examples

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

See also

variable assignment, isdefined

deal

Copy input arguments to output arguments.

Syntax

(v1, v2, ...) = deal(e)
(v1, v2, ...) = deal(e1, e2, ...)

Description

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.

Examples

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

See also

varargin, varargout, operator {}

dumpvar

Dump the value of an expression as an assignment to a variable.

Syntax

dumpvar(value)
dumpvar(name, value)
dumpvar(fd, name, value)
str = dumpvar(value)
str = dumpvar(name, value)
... = dumpvar(..., fd=fd, NPrec=nPrec)

Description

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. A file descriptor can also be specified as a named argument fd.

With an output argument, dumpvar stores result into a string and produces no output.

In addition to fd, dumpvar also accepts named argument NPrec for the maximum number of digits in floating-point numbers.

Examples

dumpvar(2+3)
  5
a = 6; dumpvar('a', a)
  a = 6;
s = 'abc'; dumpvar('string', s)
  string = 'abc';
dumpvar('x', 1/3, NPrec=5)
  x = 0.33333;

See also

fprintf, sprintf, str2obj

error

Display an error message and abort the current computation.

Syntax

error(str)
error(format, arg1, arg2, ...)
error(identifier, format, arg1, arg2, ...)
error(identifier)
error(..., throwAsCaller=b)

Description

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 can 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.

The identifier of an internal error (an error which can be thrown by an LME builti-in function, such as 'LME:indexOutOfRange'), can be used as the only argument; then the standard error message is displayed.

error also accepts a boolean named argument throwAsCaller. If it is true, the context of the error is changed so that the function calling error appears to throw the error itself. It is useful for fully debugged functions whose internal operation can be hidden. Keyword hideimplementation has a similar effect at the level of a library, by hiding the internal error handling in all its functions.

Examples

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'

Definition of a function which checks its input arguments, and a test function which calls it:

function xmax = largestRoot(a, b, c)
  // largest root of a x^2 + b x + c = 0
  if b^2 - 4 * a * c < 0
    error('No real root', throwAsCaller=true);
  end
  xmax = (-b + sqrt(b^2 - 4 * a * c)) / (2 * a);
function test
  a = largestRoot(1,1,1);

Error message:

test
No real root (test;8)

Error message without throwAsCaller=true in the definition of largestRoot:

test
No real root (largestRoot;4)
-> test;8

See also

warning, try, lasterr, lasterror, assert, fprintf, hideimplementation

eval

Evaluate the contents of a string as an expression or statements.

Syntax

x = eval(str_expression)
eval(str_statement)

Description

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.

Examples

eval('1+2')
  3
a = eval('1+2')
  a = 3
eval('a=2+3')
  a = 5

See also

feval

exist

Existence of a function or variable.

Syntax

b = exist(name)
b = exist(name, type)

Description

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 variables ('variable').

Examples

exist('sin')
  true
exist('cos', 'function')
  false

See also

info, isdefined

feval

Function evaluation.

Syntax

(argout1,...) = feval(fun,argin1,...)

Description

(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 anonymous or inline function.

If a variable f contains a function reference or an anonymous or inline function, f(arguments) is equivalent to feval(f,arguments).

Examples

y = feval('sin', 3:5)
  y =
    0.1411 -0.7568 -0.9589
y = feval(@(x) sin(2*x), 3:5)
  y =
    -0.2794 0.9894 -0.544
fun = @(x) sin(2*x);
y = fun(3:5)
  y =
    -0.2794 0.9894 -0.544

See also

builtin, eval, fevalx, apply, inline, operator @

fun2str

Name of a function given by reference or source code of an inline function.

Syntax

str = fun2str(funref)
str = fun2str(inlinefun)

Description

fun2str(funref) gives the name of the function whose reference is funref.

fun2str(inlinefun) gives the source code of the inline function inlinefun.

Examples

fun2str(@sin)
  sin
fun2str(inline('x+2*y', 'x', 'y'))
  function y=f(x,y);y=x+2*y;

See also

operator @, str2fun

info

Information about LME.

Syntax

info
info builtin
info date
info errors
info functions
info global
info libraries
info methods
info operators
info persistent
info size
info threads
info usedlibraries
info variables
info(kind, fd=fd)
str = info
SA = info(kind)

Description

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 structure array which describes each built-in function, with the following fields:

FieldDescription
namefunction name
modulemodule name
trustedtrue 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 and the line number in the source code. 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 structure array which describes each user-defined function, with the following fields:

FieldDescription
librarylibrary name
namefunction name
loadedtrue if loaded
lineline number if available, or []

info methods displays the list of methods. With an output argument, info('methods') gives a structure array which describes each method, with the following fields:

FieldDescription
librarylibrary name
classclass name
namefunction name
loadedtrue if loaded
lineline number if available, or []

info variables displays the list of variables with their type and size. With an output argument, info('variables') gives a structure array which describes each variable, with the following fields:

FieldDescription
namefunction name
definedtrue 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 the libraries they have loaded with use. The base context in which direct commands are evaluated is displayed as (base); it is not an actual library and contains no function definition. With an output argument, info('libraries') gives a structure array with the following fields:

FieldDescription
librarylibrary name, or '(base)'
sublibrarieslist of sublibraries

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 errors displays the list of error messages. With an output argument, info('errors') gives a structure array which describes each error message, with the following fields:

FieldDescription
iderror ID
msgerror message

info size displays the size in bytes of integer numbers (as used for indices and most internal computations), double numbers, single numbers, and pointers; the byte ordering in multibyte values (little-endian if the least-significant byte comes first, else big-endian), and whether arrays are stores column-wise or row-wise. With an output argument, info('size') gives them in a structure of six fields:

FieldDescription
intinteger size
doubledouble size
singlesingle size (or 0)
ptrpointer size
betrue if big-endian
columnwisetrue for column-wise array layout

info date displays the compilation date. With an output argument, info('date') gives it in a structure:

FieldDescription
dateyear, month, and day in a row vector

info threads displays the ID of all threads. With an output argument, info('threads') gives a structure array which describes each thread, with the following fields:

FieldDescription
idthread ID
totaltimeexecution time in seconds

Only the first character of the argument is meaningful; info b is equivalent to info builtin.

A named argument fd can specify the output channel; in that case, the command syntax cannot be used.

Examples

info
  LME 5.2
info s
  int: 4 bytes
  double: 8 bytes
  ptr: 4 bytes
  little endian
  array layout: row-wise
info b
  LME/abs
  LME/acos
  LME/acosh
  (etc.)
info v
  ans (1x1 complex)
vars = info('v')
  var =
    2x1 struct array (2 fields)

List of variables displayed on channel 2 (standard error channel):

info('v', fd=2)

Library hierarchy in the command-line interface:

use lti
info l
  (base): _cli, lti
  _cli: lti
  lti: polynom
  polynom

The meaning is as follows: (base) is the context where commands are evaluated; functions defined from the command-line interface, stored in _cli, and in lti can be called from there. Functions defined from the command-line interface also have access to the definitions of lti. Library lti uses library polynom, but functions defined in polynom cannot be called directly from commands (polynom does not appear as a sublibrary of (base) or _cli). Finally, library polynom does not import a sublibrary itself.

See also

inmem, which, exist, use

isequal

Comparison.

Syntax

b = isequal(a, b, ...)

Description

isequal compares its input arguments and returns true if all of them are equal, and false otherwise. Two numeric, logical and/or char arrays are considered to be equal if they have the same size and if their corresponding elements have the same value; an array which has at least one NaN (not a number) element is not equal to any other array. Two lists, cell arrays, structures or structure arrays are equal if the corresponding elements or fields are equal. Structure fields do not have to be in the same order.

isequal differs from operator == in that it results in a scalar logical value and arrays do not have to have the same size. It differs from operator === in that it does not require the type or the structure field order to agree, and in the way NaN is interpreted.

See also

operator ==, operator ===

inline

Creation of inline function.

Syntax

fun = inline(funstr)
fun = inline(expr)
fun = inline(expr, arg1, ...)
fun = inline(funstr, param)
fun = inline(expr, arg1, ..., paramstruct)
fun = inline(expr, ..., true)

Description

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 names of the arguments which must be supplied when the inline function is called, as strings; paramstruct is a structure whose fields define fixed parameters.

inline(expr,...,true) defines a function which can return as many output arguments as what feval (or other functions which call the inline function) expects. Argument expr must be a function call itself.

Anonymous functions created with operator @ 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.

Examples

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

The same function created with the anonymous function syntax:

a = 2;
fun = @(x) cos(a*x);

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})

An inline function with a variable number of output arguments:

fun = inline('eig(exp(x))',true);
e = feval(fun, magic(2))
  e =
   -28.1440
    38.2514
(V,D) = feval(fun, magic(2))
  V =
    -0.5455  -0.4921
     0.8381  -0.8705
  D =
   -28.1440   0.0000
     0.0000  38.2514

See also

function, operator @, feval, eval

inmem

List of functions loaded in memory.

Syntax

inmem
SA = inmem

Description

inmem displays the list of user-defined functions loaded in memory with the library where they are defined. With an output argument, inmem gives the result as a structure array which describes each user-defined function loaded in memory, with the following fields:

FieldDescription
librarylibrary name
classclass name ('' for functions)
namefunction name

See also

info, which

isdefined

Check if a variable is defined.

Syntax

isdefined(var)

Description

isdefined(var) returns true if variable var is defined, and false otherwise. Unlike ordinary functions, isdefined's argument must be a variable known to LME, referenced by name without quotes, and not an arbitrary expression. A variable is undefined in the following circumstances:

  • function input argument when the function call does not supply enough values;
  • function output argument which has not been assigned to, in the function itself, not in a function call;
  • function local variable before its first assignment;
  • function local variable after it has been cleared with function clear.

At command-line interface, clear usually discards completely variables.

Example

Let function f be defined as

function f(x)
  if isdefined(x)
    disp(x);
  else
    disp('Argument x is not defined.');
  end

Then

f
  Argument x is not defined.
f(3)
  3

See also

nargin, exist, which, clear, function

isfun

Test for an inline function or function reference.

Syntax

b = isfun(obj)

Description

isfun(obj) returns true if obj is an inline function or a function reference, or false otherwise.

See also

isa, class, fun2str

isglobal

Test for the existence of a global variable.

Syntax

b = isglobal(str)

Description

isglobal(str) returns true if the string str is the name of a global variable, defined as such in the current context.

See also

info, exist, isdefined, which

iskeyword

Test for a keyword name.

Syntax

b = iskeyword(str)
list = iskeyword

Description

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.

Examples

iskeyword('otherwise')
  true
iskeyword
  {'break','case','catch','continue','else','elseif',
   'end','endfunction','for','function','global',
   'hideimplementation','if','otherwise','persistent',
   'private','public','repeat','return','switch','try',
   'until','use','useifexists','while'}

See also

info, which

ismac

Check whether computer runs under macOS.

Syntax

b = ismac

Description

ismac returns true on macOS, false on other platforms.

See also

isunix, ispc

ispc

Check whether platform is a PC.

Syntax

b = ispc

Description

ispc returns true on Windows, false on other platforms.

See also

isunix, ismac

isunix

Check whether computer runs under unix.

Syntax

b = isunix

Description

isunix returns true on unix platforms (including Mac OS X and unix-like), false on other platforms.

See also

ispc, ismac

lasterr

Last error message.

Syntax

msg = lasterr
(msg, identifier) = lasterr

Description

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.

Example

x = 2;
x(3)
  Index out of range
(msg, identifier) = lasterr
  msg =
    Index out of range
  identifier =
    LME:indexOutOfRange

See also

lasterror, try, error

lasterror

Last error structure.

Syntax

s = lasterror

Description

lasterror returns a structure which describes the last error. It contains the following fields:

FieldTypeDescription
identifierstringshort tag which identifies the error
messagestringerror message

The structure can be used as argument to rethrow in the catch part of a try/catch construct to propagate the error further.

Example

x = 2;
x(3)
  Index out of range
lasterror
  message: 'Index out of range'
  identifier: 'LME:indexOutOfRange'

See also

lasterr, try, rethrow, error

namedargin

Named input arguments.

Syntax

function ... = fun(..., namedargin)

Description

namedargin is a special variable which can be used to collect named input arguments. In the function declaration, it must be used as the last (or unique) input argument. When the function is called with named arguments, all of them are collected and stored in namedargin as a structure, where field names correspond to the argument names. With namedargin, there is no matching between the named arguments and the argument names in the function declaration. If the function is called without any named argument, namedargin is set to an empty structure.

In the body of the function, namedargin is a normal variable. Its fields can be accessed with the dot notation namedargin.name or namedargin.(name). All functions using structures can be used, such as fieldnames or isfield. namedargin can also be modified or assigned to any value of any type.

When both varargin (for a variable number of unnamed arguments) and namedargin are used in the same function, they must be the last-but-one and the last arguments in the function declaration, respectively.

Example

Here is a function which calculates the volume of a solid of revolution defined by a function y=f(x) between x=a and x=b, rotating around y=0. It accepts the same options as integral, given as a single option argument, as named values or both.

function V = solidRevVolume(fun, a, b, opt=struct, namedargin)
  opt = structmerge(opt, namedargin);
  V = pi * integral(@(x) fun(x)^2, a, b, opt);

It can be called without any option (opt is set to its default value, an empty structure):

cyl = solidRevVolume(@(x) 1, 0, 1)
  cyl = 3.1416
cone = solidRevVolume(@(x) x, 0, 2, RelTol=1e-4)
  cone = 8.3776

See also

varargin, function, struct, fieldnames, structmerge, operator .

nargin

Number of input arguments.

Syntax

n = nargin
n = nargin(fun)

Description

Calling a function with less arguments than what the function expects is permitted. In this case, the trailing variables are not defined. The function can use the nargin function to know how many arguments were passed by the caller to avoid accessing the undefined variables. Named arguments (arguments passed as name=value by the caller) are not included in the count.

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 three other ways to let a function accept a variable number of input arguments: to check if an input argument is defined with isdefined, 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 an input argument, nargin(fun) returns the (maximum) number of input arguments a function accepts. fun can 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.

Examples

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 called as the infix operator "+"):

nargin('plus')
  2

See also

nargout, varargin, isdefined, function

nargout

Number of output arguments.

Syntax

n = nargout
n = nargout(fun)

Description

A function can 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 can 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.

Example

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

See also

nargin, varargout, function

rethrow

Throw an error described by a structure.

Syntax

rethrow(s)
rethrow(s, throwAsCaller=b)

Description

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.

rethrow also accepts a boolean named argument throwAsCaller. If it is true, the context of the error is changed so that the function calling rethrow appears to throw the error itself. It is useful for fully debugged functions whose internal operation can be hidden.

Example

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

See also

lasterror, try, error

str2fun

Function reference.

Syntax

funref = str2fun(str)

Description

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.

Examples

str2fun('sin')
  @sin
@sin
  @sin
a = 'cos';
str2fun(a)
  @cos

See also

operator @, fun2str

str2obj

Convert to an object its string representation.

Syntax

obj = str2obj(str)

Description

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.

Examples

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

See also

eval, dumpvar

varargin

Remaining input arguments.

Syntax

function ... = fun(..., varargin)
function ... = fun(..., varargin, namedargin)
l = varargin

Description

varargin is a special variable which can be used to collect input arguments. In the function declaration, it must be used after the normal input arguments; if namedargin is also present, varargin immediately precedes it. 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 can 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, {}.

Example

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

See also

nargin, namedargin, varargout, function

varargout

Remaining output arguments.

Syntax

function (..., varargout) = fun(...)
varargout = ...

Description

varargout is a special variable which can 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 can be used to know how many output arguments to produce.

Example

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

See also

nargout, varargin, function

variables

Contents of the variables as a structure.

Syntax

v = variables

Description

variables returns a structure whose fields contain the variables defined in the current context.

Example

a = 3;
b = 1:5;
variables
  a: 3
  b: real 1x5
  ...

See also

info

warning

Write a warning to the standard error channel.

Syntax

warning(msg)
warning(format, arg1, arg2, ...)

Description

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.

Example

warning('Doesn\'t converge.');

See also

error, disp, fprintf

which

Library where a function is defined.

Syntax

fullname = which(name)

Description

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); a variable, with (var); and a keyword, with (keyword). If name is unknown, which returns the empty string.

Examples

which logspace
  stdlib/logspace
which polynom::plus
  polynom/polynom::plus
which sin
  (builtin)/sin
x = 2;
which x
  (var)/x

See also

info, isdefined