You are on page 1of 46

Matlab Programming (II)

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.

• They operate on variables within their


own workspace, which is separate from
the workspace you access at the
MATLAB command prompt.
© IAMSR 5
Simple Function Example
function y = average(x)
% AVERAGE Mean of vector elements.
% AVERAGE(X), where X is a vector, is the mean of vector elements.
% Nonvector input results in an error.
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))
error('Input must be a vector')
end
y = sum(x)/length(x); % Actual computation

• To call the average function, enter:


z = 1:99;
average(z)
ans =
50
© IAMSR 6
Basic Parts of a Function M-File
The Function Definition Line
• The function definition line informs MATLAB that the M-file contains a function

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

• This is the first line of text that appears when a user


types help function_name at the MATLAB prompt.
Because this line provides important summary
information about the M-file, it is important to make it as
descriptive as possible.
8
© IAMSR
Help Text
• You can create online help for your M-files by entering text on
one or more comment lines, beginning with the line immediately
following the H1 line. The help text for the average function is

% AVERAGE(X), where X is a vector, is the mean of vector elements.


% Nonvector input results in an error.

• When you type help function_name, MATLAB displays the


comment lines that appear between the function definition line and
the first non-comment (executable or blank) line. The help system
ignores any comment lines that appear after this help block.

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.

• The building blocks of expressions are:


• Variables
• Numbers
• Operators
• Functions
11
© IAMSR
Variables
• You do not need to type or declare variables
used in M-files, (with the possible exception of
designating them as global or persistent).
• Before assigning one variable to another, you
must be sure that the variable on the right-hand
side of the assignment has a value.
• Any operation that assigns a value to a variable
creates the variable, if needed, or overwrites its
current value, if it already exists.
12
© IAMSR
Naming Variables
• MATLAB variable names must begin with a letter, which may be followed
by any combination of letters, digits, and underscores.
• MATLAB distinguishes between uppercase and lowercase characters, so A
and a are not the same variable.
• Although variable names can be of any length, MATLAB uses only the
first N characters of the name, (where N is the number returned by the
function namelengthmax), and ignores the rest. Hence, it is important to
make each variable name unique in the first N characters to enable
MATLAB to distinguish variables.
N = namelengthmax
N=
63
• When naming a variable, make sure you are not using a name that is
already used as a function name. If you define a variable with a function
name, you won't be able to call that function until you either clear the
variable from memory, or invoke the function using builtin.

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.

• Any assignment to that variable, in any function, is


available to all the other functions declaring it global.

Ex.:
global ALPHA BETA
ALPHA = 0.01
BETA = 0.02

• There is a certain amount of risk associated with using


global variables and, because of this, it is recommended
that you use them sparingly. 15
Persistent Variables
Characteristics of persistent variables are:
• You can only use them in functions.
• Other functions are not allowed access to them.
• MATLAB does not clear them from memory when the
function exits, so their value is retained from one function
call to the next.
• If you clear the function or edit the M-file for that
function, then MATLAB clears all persistent variables
used in that function.

You must declare persistent variables as persistent before


you can use them in a function.

Ex:
persistent SUM_X 16
Numbers
• MATLAB uses conventional decimal notation, with an optional
decimal point and leading plus or minus sign, for numbers.

• Scientific notation uses the letter e to specify a power-of-ten scale


factor. Imaginary numbers use either i or j as a suffix.

• 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

.^ Power ^ Matrix power


: Colon operator

Except for some matrix operators, MATLAB arithmetic operators work on


corresponding elements of arrays with equal dimensions.
20
© IAMSR
Relational Operators
• The MATLAB relational operators Operator Description
compare corresponding elements
of arrays with equal dimensions. Less than
<
• Relational operators always
operate element-by-element.
<= Less than or
• For the case where one operand is
equal to
a scalar and the other is not,
MATLAB tests the scalar against > Greater than
every element of the other
operand. >= Greater than or
• Locations where the specified equal to
relation is true receive the value 1.
== Equal to
• Locations where the relation is
false receive the value 0.
~= Not equal to

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)

xor xor(A,B)=10100 ~A not(A)

Function Description Example


any(A) Returns 1 for a vector (column) where at any(A)
A = [0 1 2; least one element of the vector is true ans =0 1 1
0 -3 8; (nonzero), and 0 if no elements are true.
0 5 0]; all(A) Returns 1 for a vector (column) where all all(A)
elements of the vector are true (nonzero), ans =0 1 0
and 0 if all elements are not true.
23
© IAMSR
Bit-Wise Functions
• Inputs may be scalar or in arrays. If in arrays, these functions produce a
like-sized output array.

• Ex.: A = 28; % binary 11100


B = 21; % binary 10101

Function Description Example


bitand Returns the bit-wise AND of two bitand(A,B) = 20
nonnegative integer arguments. (binary 10100)
bitor Returns the bit-wise OR of two bitor(A,B) = 29
nonnegative integer arguments. (binary 11101)
bitcmp Returns the bit-wise complement as an n- bitcmp(A,5) = 3
bit number, where n is the second input (binary 00011)
argument to bitcmp.
bitxor Returns the bit-wise exclusive OR of two bitxor(A,B) = 9
nonnegative integer arguments. (binary 01001)
24
© IAMSR
Short-Circuit Operators
• The following operators perform AND and OR operations on logical expressions
containing scalar values.
• They are short-circuit operators in that they only evaluate their second operand when
the result is not fully determined by the first operand.

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.

• To list the keywords, type

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

• If the logical_expression is true (1), MATLAB executes all the


statements between the if and end lines.

• If the condition is false (0), MATLAB skips all the statements


between the if and end lines.

• The else and elseif statements further conditionalize the if


statement. 33
© IAMSR
Example of if, else, and elseif
if n < 0
disp('Input must be positive');
elseif rem(n,2) == 0 % If n positive and even, divide by 2.
A = n/2;
else
A = (n+1)/2; % If n positive and odd, increment and divide.
end

34
© IAMSR
switch
Syntax:

switch expression (scalar or string)


case value1
statements % Executes if expression is value1
case value2
statements % Executes if expression is value2
.
.
.
otherwise
statements % Executes if expression does not match any case
end
35
© IAMSR
Example of switch
switch input_num
case -1
disp('negative one');
case 0
disp('zero');
case 1
disp('positive one');
otherwise
disp('other value');
end

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 example, consider an m-by-n array A, the statement:

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.

• In nested loops, continue passes control to the next


iteration of the for or while loop enclosing it.

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.

• When a break statement is encountered,


execution continues with the next statement
outside of the loop.

• In nested loops, break exits from the innermost


loop only.
42
© IAMSR
Example of break
while expression
statemets1
if condition
break
statements2
end
statements3
43
© IAMSR
try ... catch
Syntax:

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.

• return is also used to terminate keyboard mode.

• A called function normally transfers control to the


function that invoked it when it reaches the end of the
function.

• return may be inserted within the called function to force


an early termination and to transfer control to the 45
invoking function.
Example of return
function d = det(A)
%DET det(A) is the determinant of A.
if isempty(A)
d = 1;
return
else
...
end
46
© IAMSR

You might also like