Programming Structures

Programming structures are the backbone of any LME program. Except for the variable assignment, all of them use reserved keywords which may not be used to name variables or functions. In addition to the structures described below, the following keywords are reserved for future use:

builtin
global
goto
label
persistent
repeat
until
 
 

Variable assignment

Assignment to a variable or to some elements of a matrix variable.

Syntax

var = expr
(var1, var2, ...) = function(...)

Description

var = expr assigns the result of the expression expr to the variable var. When the expression is a naked function call, (var1,var2,...) = function(...) assigns the value of the output arguments of the function to the different variables. Usually, providing less variables than the function can provide just discards the superfluous output arguments; however, the function can also choose to perform in a different way (an example of such a function is size, which returns the number of rows and the number of columns of a matrix either as two numbers if there are two output arguments, or as a 1-by-2 vector if there is a single output argument). Providing more variables than what the function can provide is an error.

Variables can store any content dynamically: the size and type can change from assignment to assignment.

A subpart of a matrix variable can be replaced with the use of parenthesis. In this case, the size of the variable is expanded when required.

See also

operator (), clear, exist, for

function

Definition of a function, operator, or method.

Syntax

function f
  statements

function f(x1, x2, ...)
  statements

function f(x1, x2 = expr2, ...)
  statements

function y = f
  statements

function y = f(x1, x2, ...)
  statements

function (y1,y2,...) = f(x1,x2,...)
  statements

function ... class::method ...

Description

New functions can be written to extend the capabilities of LME. They begin with a line containing the keyword function, followed by the list of output arguments (if any), the function name, and the list of input arguments between parenthesis (if any). The output arguments must be enclosed between parenthesis or square brackets if they are several. One or more variable can be shared in the list of input and output arguments. When the execution of the function terminates (either after the last statement or because of the command return), the current value of the output arguments, as set by the function's statements, is given back to the caller. All variables used in the function's statements are local; their value is undefined before the first assignment (and it is illegal to use them in an expression), and is not shared with variables in other functions or with recursive calls of the same function.

Not all of the input and output arguments are necessarily used. The caller fixes the number of input and output arguments, which can be retrieved by the called function with nargin and nargout, respectively. The unused input arguments (from nargin+1 to the last one) are undefined, unless a default value is provided in the function definition: with the definition function f(x,y=2), y is 2 when f is called with a single input argument. The unused output arguments (from nargout+1 to the last one) do not have to be set, but may be.

To redefine an operator (which is especially useful for object methods; see below), use the equivalent function, such as plus for operator +. The complete list is given in the section about operators.

To define a method which is executed when one of the input arguments is an object of class class (or a child in the classes hierarchy), prepend class:: to the method (function) name. To call it, use only the method name, not the class name.

Examples

Function with optional input and output arguments:

function (Sum, Prod) = calcSumAndProd(x, y)
  if nargout == 0
    return;           % nothing to be computed
  end
  if nargin == 0      % make something to be computed...
    x = 0;
  end
  if nargin <= 1      % sum of elements of x
    Sum = sum(x);
  else                % sum of x and y
    Sum = x + y;
  end
  if nargout == 2     % also compute the product
    if nargin == 1    % product of elements of x
      Prod = prod(x);
    else              % product of x and y
      Prod = x .* y;
    end
  end  

Two equivalent definitions:

function S = area(a, b = a, ellipse = false)
  S = ellipse ? pi * a * b / 4 : a * b;
function S = area(a, b, ellipse)
  if nargin < 2
    y = x;
  end
  if nargin < 3
    b = false;
  end
  S = ellipse ? pi * a * b / 4 : a * b;

See also

return, nargin, nargout, define, inline

return

Early return from a function.

Syntax

return

Description

return stops the execution of the current function and returns to the calling function. The current value of the output arguments, if any, is returned. return can be used in any control structure, such as if, while, or try, or at the top level.

Example

function dispFactTable(n)
  % display the table of factorials from 1 to n
  if n == 0
    return;  % nothing to display
  end
  fwrite(' i   i!\n');
  for i = 1:n
    fwrite('%2d  %3d\n', i, prod(1:i));
  end
  

See also

function

define

Definition of a constant.

Syntax

define c = expr
define c = expr;

Description

define c=expr assign permanently expression expr to c. It is equivalent to

function y = c
  y = expr;

Since c does not have any input argument, the expression is usually constant. A semicolon may follow the definition, but it does not have any effect.

Examples

define e = exp(1);
define g = 9.81;
define c = 299792458;
define G = 6.672659e-11;

See also

function

if elseif else

Conditional execution depending on the value of one or more boolean expressions.

Syntax

if expr
    s1
    ...
end

if expr
    s1
    ...
else
    s2
    ...
end

if expr1
    s1
    ...
elseif expr2
    s2
    ...
else
    s3
    ...
end

Description

If the expression following if is true (nonempty and all elements different from 0 and false), the statements which follow are executed. Otherwise, the expressions following elseif are evaluated, until one of them is true. If all expressions are false, the statements following else are executed. Both elseif and else are optional.

Example

if x > 2
  disp('large');
elseif x > 1
  disp('medium');
else
  disp('small');
end

See also

switch

switch case otherwise

Conditional execution of statements depending on a number or a string.

Syntax

switch expr
    case e1
        s1
        ...
    case [e2,e3,...]
        s23
        ...
    case {e4,e5,...}
        s45
        ...
    otherwise
        so
        ...
end

switch string
    case str1
        s1
        ...
    case str2
        s2
        ...
    case {str3,str4,...}
        s34
        ...
    otherwise
        so
        ...
end

Description

The expression of the switch statement is evaluated. If it yields a number, it is compared successively to the result of the expressions of the case statements, until it matches one; then the statements which follow the case are executed until the next case, otherwise or end. If the case expression yields a vector or a list, a match occurs if the switch expression is equal to any of the elements of the case expression. If no match is found, but otherwise is present, the statements following otherwise are executed. If the switch expression yields a string, a match occurs only in case of equality with a case string expression or any element of a case list expression.

Example

switch option
  case 'arithmetic'
    m = mean(data);
  case 'geometric'
    m = prod(data)^(1/length(data));
  otherwise
    error('unknown option');
end

See also

if

while break continue

Loop controlled by a boolean expression.

Syntax

while expr
    s1
    ...
end

while expr
    s1
    ...
    if ...
        break
    end
    ...
    if ...
        continue
    end
    ...
end

Description

The statements between the while statement and the corresponding end are executed repeatedly as long as the expression of the while statement yields true (nonempty and all elements different from 0 and false).

If a break statement is executed in the scope of the while loop (i.e. not in an enclosed loop), the loop is terminated.

If a continue statement is executed in the scope of the while loop (i.e. not in an enclosed loop), statements following continue are ignored and a new loop is performed if the while statement yields true.

Example

e = 1;
i = 2;
while true  % forever
  eNew = (1 + 1/i) ^ i;
  if abs(e - eNew) < 0.001
    break;
  end
  e = eNew;
  i = 2 * i;
end
e
  2.717

See also

for

for break continue end

Loop controlled by a variable which takes successively the value of the elements of a vector or a list.

Syntax

for v = vect
    s1
    ...
end

for v = list
    s1
    ...
end

for v = ...
    s1
    ...
    if ...
        break
    end
    ...
    if ...
        continue
    end
    ...
end

Description

The statements between the for statement and the corresponding end are executed repeatedly with the control variable v taking successively every column of vect or every element of list list. Typically, vect is a row vector defined with the range operator.

If a break statement is executed in the scope of the for loop (i.e. not in an enclosed loop), the loop is terminated, and the control variable keeps its current value.

If a continue statement is executed in the scope of the for loop (i.e. not in an enclosed loop), statements following continue are ignored and a new loop is performed if vect is not consumed.

You can change the value of the control variable in the loop; however, next time the loop is repeated, that value is discarded and the next column of vect is fetched.

Examples

for i = 1:3; i, end
  i =
    1
  i =
    2
  i =
    3
for i = (1:3)'; i, end
  i =
    1
    2
    3
for i = 1:2:5; end; i
  i =
    5
for i = 1:3; break; end; i
  i =
    1
for el = {1,'abc',{2,5}}; el, end
  el =
    1
  el =
    abc
  el =
    {2,5}

See also

while, variable assignment

try catch

Error recovery.

Syntax

try
  ...
end

try
  ...
catch
  ...
end

Description

The statements after try are executed. If an error occurs, execution is switched to the statements following try, if any, or to the statements following end. The error message can be retrieved with lasterr. If no error occurs, the statements between try and end are ignored.

Examples

a = 1;
a(2), 555
  Index out of range 'a'
try, a(2), end, 555
  555
try, a(2), catch, 333, end, 555
  333
  555
try, a, catch, 333, end, 555
  a =
    1
  555

See also

lasterr, error

use

Import one or more libraries.

Syntax

use lib
use lib1, lib2, ...

Description

Functions may be defined in separate files, called libraries. use makes them available in the current context, so that they may be called by the functions or statements which follow. Using a library does not make available functions defined in the sublibrary; however, libraries may be used multiple times, in each context where their functions are referenced.

See also

function, private, public, info

private

Mark the beginning of a sequence of private function definitions in a library.

Syntax

private

Description

In a library, functions which are defined after the private keyword are private. private may not be placed in the same line of source code as any other command (comments are possible, though).

In a library, function are either public or private. Private functions can only be called from the same library, while public functions can also be called from contexts where the library has been imported with a use command. Functions are public by default.

Example

Here is a library for computing the roots of a second-order polynomial. Only function roots2 may be called from the outside of the library.

private
function d = discr(a, b, c)
  d = b^2 - 4 * a * c;
public
function r = roots2(p)
  a = p(1);
  b = p(2);
  c = p(3);
  d = discr(a, b, c);
  r = [-b+sqrt(d); -b-sqrt(d)] / (2 * a);

See also

public, function, use

public

Mark the beginning of a sequence of public function definitions in a library.

Syntax

public

Description

In a library, functions which are defined after the public keyword are public. public may not be placed in the same line of source code as any other command (comments are possible, though).

In a library, function are either public or private. Private functions can only be called from the same library, while public functions can also be called from contexts where the library has been imported with a use command. Functions are public by default: the public keyword is not required at the beginning of the library.

See also

private, function, use


Copyright 1998-2001, Calerga.

All rights reserved.