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:
|
|
|
Assignment to a variable or to some elements of a matrix variable.
var = expr (var1, var2, ...) = function(...)
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.
operator (), clear, exist, for
Definition of a function, operator, or method.
function f statements function f(x1, x2, ...) statements function y = f statements function y = f(x1, x2, ...) statements function (y1,y2,...) = f(x1,x2,...) statements function ... class::method ...
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; 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.
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
return, nargin, nargout, define, inline
Early return from a function.
return
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.
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
Definition of a constant.
define c = expr define c = expr;
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.
define e = exp(1); define g = 9.81; define c = 299792458; define G = 6.672659e-11;
Conditional execution depending on the value of one or more boolean expressions.
if expr s1 ... end if expr s1 ... else s2 ... end if expr1 s1 ... elseif expr2 s2 ... else s3 ... end
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.
if x > 2 disp('large'); elseif x > 1 disp('medium'); else disp('small'); end
Conditional execution of statements depending on a number or a string.
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
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.
switch option case 'arithmetic' m = mean(data); case 'geometric' m = prod(data)^(1/length(data)); otherwise error('unknown option'); end
Loop controlled by a boolean expression.
while expr s1 ... end while expr s1 ... if ... break end ... if ... continue end ... end
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.
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
Loop controlled by a variable which takes successively the value of the elements of a vector or a list.
for v = vect s1 ... end for v = list s1 ... end for v = ... s1 ... if ... break end ... if ... continue end ... end
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.
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}
Error recovery.
try ... end try ... catch ... end
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.
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
Import one or more libraries.
use lib use lib1, lib2, ...
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.
function, private, public, info
Mark the beginning of a sequence of private function definitions in a library.
private
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.
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);
Mark the beginning of a sequence of public function definitions in a library.
public
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.