Professional Documents
Culture Documents
Iulian Nastac
© IAMSR
REMEMBER
Kinds of M-Files
Script M-Files Function M-Files
Do not accept input Can accept input
arguments or return output arguments and return
arguments output arguments
Operate on data in the Internal variables are local
workspace to the function by default
Useful for automating a Useful for automating a
series of steps you need to series of steps you need to
perform many times perform many times
© IAMSR 2
REMEMBER
Scripts
• Scripts are the simplest kind of M-file because they
have no input or output arguments.
• They're useful for automating series of MATLAB
commands, such as computations that you have to
perform repeatedly from the command line.
• Scripts operate on existing data in the workspace, or
they can create new data on which to operate.
• Any variables that scripts create remain in the
workspace after the script finishes so you can use
them for further computations.
© IAMSR 3
Script Example
% An M-file script to produce % Comment lines
% "flower petal" plots
theta = -pi:0.01:pi; % Computations
rho(1,:) = 2*sin(5*theta).^2;
rho(2,:) = cos(10*theta).^3;
rho(3,:) = sin(theta).^2;
rho(4,:) = 5*cos(3.5*theta).^3;
for k = 1:4
polar(theta,rho(k,:)) % Graphics output
pause
end
© IAMSR 4
Functions
• Functions are M-files that accept input
arguments and return output arguments.
• The function name must begin with a letter, which may be followed by any
combination of letters, digits, and underscores.
• The name of the text file that contains a MATLAB function consists of the function
name with the extension .m appended.
7
© IAMSR
The H1 Line
• The H1 line, so named because it is the first help text
line, is a comment line immediately following the
function definition line. Because it consists of comment
text, the H1 line begins with a percent sign, "%." For the
average function, the H1 line is
% AVERAGE Mean of vector elements.
9
© IAMSR
The Function Body
• The function body contains all the MATLAB code that
performs computations and assigns values to output
arguments.
• For example:
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1)) % Flow control
error('Input must be a vector') % Error message display
end
y = sum(x)/length(x); % Computation and assignment
10
© IAMSR
Expressions
• Like most other programming languages,
MATLAB provides mathematical expressions,
but unlike most programming languages, these
expressions involve entire matrices.
13
© IAMSR
Local Variables
• Each MATLAB function has its own local variables.
These are separate from those of other functions, and
from those of the base workspace.
• Variables defined in a function do not remain in
memory from one function call to the next, unless
they are defined as global or persistent.
• Scripts, on the other hand, do not have a separate
workspace. They store their variables in a workspace
that is shared with the caller of the script. When
called from the command line, they share the base
workspace. When called from a function, they share
that function's workspace.
14
© IAMSR
Global Variables
• If several functions, and possibly the base workspace, all
declare a particular name as global, then they all share a
single copy of that variable.
Ex.:
global ALPHA BETA
ALPHA = 0.01
BETA = 0.02
Ex:
persistent SUM_X 16
Numbers
• MATLAB uses conventional decimal notation, with an optional
decimal point and leading plus or minus sign, for numbers.
• Ex.:
3 0.0001 1.60210e-20 -3.14159j
• All numbers are stored internally using the long format specified
by the IEEE floating-point standard. Floating-point numbers have
a finite precision of roughly 16 significant decimal digits and a
finite range of roughly 10-308 to 10+308.
17
© IAMSR
Making Sure Variable Names Are
Valid
• Before using a new variable name, you can check to see if it is
valid with the isvarname function.
• Note that isvarname does not consider names longer than
namelengthmax characters to be valid.
• For example, the following name cannot be used for a variable
since it begins with a number.
isvarname 8th_column
ans =
0 % Not valid - begins with a number
isvarname foo
ans =
1 % This variable name is valid
18
© IAMSR
Operators
The MATLAB operators fall into three categories:
• Arithmetic operators that perform numeric
computations, for example, adding two numbers or
raising the elements of an array to a given power.
• Relational operators that compare operands
quantitatively, using operators like "less than" and
"not equal to."
• Logical operators that use the logical operators
AND, OR, and NOT.
19
© IAMSR
Arithmetic Operators
Operator Description Operator Description
+ Addition .' Transpose
- Subtraction ' Complex conjugate
transpose
.* Multiplication * Matrix
multiplication
./ Right division / Matrix right
division
.\ Left division \ Matrix left division
21
© IAMSR
Logical Operators
MATLAB offers three types of logical
operator and functions:
• Element-wise -- operate on corresponding
elements of logical arrays.
• Bit-wise -- operate on corresponding bits of
integer values or arrays.
• Short-circuit -- operate on scalar, logical
expressions.
22
© IAMSR
Element-Wise Operators and Functions
A = [0 1 1 0 1] B = [1 1 0 0 1]
Operator Example Logical Operation Equivalent
Function
& A & B = 01001
A&B and(A,B)
| A | B = 11101
~ ~A = 10010 A|B or(A,B)
Operator Description
&& Returns true (1) if both inputs evaluate to true, and false (0) if
they do not.
|| Returns true (1) if either input, or both, evaluate to true, and
false (0) if they do not.
Use the && and || operators in if and while statements to take advantage of their
short-circuiting behavior:
if (nargin >= 3) && (ischar(varargin{3}))
25
© IAMSR
Operator Precedence
1. Parentheses ()
2. Transpose (.'), power (.^), complex conjugate transpose ('),
matrix power (^)
3. Unary plus (+), unary minus (-), logical negation (~)
4. Multiplication (.*), right division (./), left division(.\), matrix
multiplication (*), matrix right division (/), matrix left division
(\)
5. Addition (+), subtraction (-)
6. Colon operator (:)
7. Less than (<), less than or equal to (<=), greater than (>),
greater than or equal to (>=), equal to (==), not equal to (~=)
8. Element-wise AND (&)
9. Element-wise OR (|)
10. Short-circuit AND (&&)
11. Short-circuit OR (||)
26
© IAMSR
Functions
• MATLAB provides a large number of standard elementary mathematical
functions, including abs, sqrt, exp, and sin.
• Taking the square root or logarithm of a negative number is not an error;
the appropriate complex result is produced automatically.
• MATLAB also provides many more advanced mathematical functions,
including Bessel and gamma functions.
• Most of these functions accept complex arguments.
• For a list of the elementary mathematical functions, type
help elfun
• For a list of more advanced mathematical and matrix functions, type
help specfun
help elmat
• Some of the functions, like sqrt and sin, are built in. They are part of the
MATLAB core so they are very efficient, but the computational details are
not readily accessible.
• Other functions, like gamma and sinh, are implemented in M-files. You can
see the code and even modify it if you want. 27
Several special functions provide values of
useful constants:
pi 3.14159265...
i Imaginary unit, −1
j Same as i
eps Floating-point relative precision, 2-52
realmin Smallest floating-point number, 2-1022
realmax Largest floating-point number, (2-ε)21023
Inf Infinity
NaN Not-a-number
28
© IAMSR
Observations:
• Infinity (Inf) is generated by dividing a nonzero value by
zero, or by evaluating well defined mathematical expressions
that overflow, i.e., exceed realmax.
• Not-a-number (NaN) is generated by trying to evaluate
expressions like 0/0 or Inf-Inf that do not have well defined
mathematical values.
• The function names are not reserved. It is possible to
overwrite any of them with a new variable, such as
eps = 1.e-6
and then use that value in subsequent calculations.
• The original function can be restored with
clear eps
29
© IAMSR
Examples of Expressions
rho = (1+sqrt(5))/2
rho =
1.6180
z = sqrt(besselk(4/3,rho-i))
z=
0.3730+ 0.3214i
huge = exp(log(realmax))
huge =
1.7977e+308
toobig = pi*huge
toobig =
Inf 30
Keywords
• MATLAB reserves certain words for its own use as keywords of the
language.
iskeyword
ans =
'break' 'global'
'case' 'if'
'catch' 'otherwise'
'continue' 'persistent'
'else' 'return'
'elseif' 'switch'
'end' 'try'
'for' 'while'
'function'
31
© IAMSR
Instructions (Flow Control)
There are eight flow control statements in MATLAB:
• if, together with else and elseif, executes a group of statements based
on some logical condition.
• switch, together with case and otherwise, executes different groups of
statements depending on the value of some logical condition.
• while executes a group of statements an indefinite number of times,
based on some logical condition.
• for executes a group of statements a fixed number of times.
• continue passes control to the next iteration of a for or while loop,
skipping any remaining statements in the body of the loop.
• break terminates execution of a for or while loop.
• try...catch changes flow control if an error is detected during
execution.
• return causes execution to return to the invoking function.
All flow constructs use end to indicate the end of the flow control block.
32
© IAMSR
if, else, and elseif
Syntax:
if logical_expression
statements
end
34
© IAMSR
switch
Syntax:
Note: unlike the C language, break statements are not used during switch
36
© IAMSR
while
Syntax:
while expression
statemets
end
Ex:
n = 1;
while n < 10
n = n + 1;
end 37
© IAMSR
for
Syntax:
for index = start:increment:stop
statements
end
Ex:
for i = 2:6
x(i) = 2*x(i-1);
end
38
© IAMSR
Using Arrays as Indices
• The index of a for loop can be an array.
for i = A
statements
end
sets i equal to the vector A(:,k). For the first loop iteration, k is
equal to 1; for the second k is equal to 2, and so on until k
equals n. That is, the loop iterates for a number of times equal
to the number of columns in A. For each iteration, i is a vector
containing one of the columns of A. 39
continue
• The continue statement passes control to the next
iteration of the for or while loop in which it
appears, skipping any remaining statements in the
body of the loop.
40
© IAMSR
Example of continue
while expression
statemets1
if condition
continue
end
statements2
end
41
© IAMSR
break
• The break statement terminates the execution
of a for loop or while loop.
try,
statement,
...,
statement,
catch,
statement,
...,
statement,
end
• In this sequence the statements between try and catch are executed until an error
occurs.
• The statements between catch and end are then executed.
• Use lasterr to see the cause of the error.
• If an error occurs between catch and end, MATLAB terminates execution unless
another try ... catch sequence has been established.
44
© IAMSR
return
• return terminates the current sequence of commands and
returns control to the invoking function or to the
keyboard.