Title: MATLAB PROGRAMMING
1 MATLAB PROGRAMMING
- M-Files Editor
- M-Files scripts and functions
- Program Control Statements
- Types of Functions
- Calling Functions
- Optimizing for Speed
- Profiler
- Inline function
- Function Handles
2M-Files Editor
3M-Files scripts and functions
.m
Type of M-file
- MATLAB scripts
- Are useful for automating a series of steps
you need to perform many times. - Do not accept input arguments or return output
arguments. - Store variables in a workspace that is shared
with other scripts and with the MATLAB command
line interface. - MATLAB functions
- Are useful for extending the MATLAB language
for your application. - Can accept input arguments and return output
arguments. - Store variables in a workspace internal to the
function.
4Types of M-Files
M-file scripts
- Scripts share workspace with interactive MATLAB
session and with other scripts. - They operate on existing data in the workspace,
or create new data on which to operate. - Any variables that scripts create remain in the
workspace after the script finishes - Be aware that running a script can
unintentionally overwrite data stored in the base
workspace
5 Types of M-Files
M-file functions
- Functions are program usually implemented in
M-files, that accept input and return output
arguments. - They operate on variables within their own
workspace which separate from the MATLAB base
workspace . - The variables that pass to a function must be in
the calling context, and the function returns its
output arguments to the calling workspace
context. You can, however, define global
variables explicitly, allowing more than one
workspace context to access them.
6 Basic Parts of an M-File
function f fact(n)
Function definition line Compute a
factorial value. H1 line
FACT(N) returns the factorial of N, Help
text usually denoted by N! Put simply,
FACT(N) is PROD(1N). Comment f prod(1n)
Function
body
7Program Control Statements
Loop Control - for, while, continue, break
1. for-end loop executes a predetermined number
of times. for index startincrementend
statements end 2. while-end loop
executes repeatedly as long as the controlling
expression is true. while expression
statements end If expression is a matrix, all
its elements must be true for execution to
continue.
for k matrix statements end
8Program Control Statements
3.Continue continue passes control to the next
iteration of for or while loop, skipping any
remaining statements in current loop. In nested
loops, continue passes control to the next
iteration of the for or while loop enclosing
it. 4. break break 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.
9Program Control Statements
Conditional Control - if, switch
- 1. if-end-else, elseif
- if evaluates a logical expression, if logical
expression is true, MATLAB executes all the
statements between if and end lines. - if logical_expression
- statements
- end
- else and elseif
- else has no logical condition, it execute when
the preceding if (possibly elseif condition)
evaluates to false. - elseif has a logical condition, it evaluates if
the preceding if (possibly elseif condition) is
false. it execute when its logical condition
evaluates to true.
10Program Control Statements
2. switch, case, and otherwise 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
11 Program Control Statements
Error Control -- try, catch
- 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,
terminates execution unless another try-catch
sequence has been established.
try statement ... catch statement
... end
12 Program Control Statements
Other Statements-- return, pause,
input, keyboard
return terminates the current sequence of
commands and returns control to the invoking
function or to the keyboard. pause causes
M-files to stop and wait for pressing any key
before continuing. pause(n) pauses execution for
n seconds before continuing. keyboard when
placed in an M-file, stops execution of the file
and gives control to the keyboard. To terminate
the keyboard mode, type return input Request
user input
13Types of Functions
Primary M-File Functions The first function
in M-file is called primary function. Nested
Functions Functions defined within the body
of another function Subfunctions Any
functions that follow the primary function in an
M-file Private Functions Functions with
restricted access, callable only from an M-file
function in the parent directory Anonymous
Functions Functions defined from a expression,
without requiring an M-file Overloaded
Functions Functions with multiple
implementations that respond to different types
of inputs accordingly
14Calling Functions
1. Local Variables and Global Variables Local
Variables It be used only in function
scope Global Variables If you want more than one
function to share a variable, declare the
variable as global in all the functions. 2.
Function Syntax out functionname(in1, in2, ...,
inN) out1, out2, ..., outN functionname(in1,
in2, ..., inN) 3. Passing Arguments A pi
str1 'one' str2
'one' disp(A) Function syntax
strcmp(str1, str2) Function syntax 3.1416
ans
1
15 Calling Functions
- 4. Arguments Numbers
- nargin returns number of input arguments
specified for a function. - nargout returns number of output arguments
specified for a function. - nargin(fun) returns the number of declared
inputs for the function. - nargout(fun) returns the number of declared
outputs for the function. - fun-may be the name of function or function
handle. - 5. Pass any number of inputs varargin
- Return any number of outputs arargout
- function varargout fun(n) returns a variable
number of arguments - from function
fun.m. - function y fun(varargin) accepts a variable
number of arguments - into function fun.m.
16 Calling Functions
Programming Example Ploting the curves with
different damps Zeta0,0.3,0.707
17Optimizing for Speed
- You can save a preparsed version of a
function or script, called P-code files .p, for
later MATLAB sessions using the pcode function. - pcode filename
- pcode filename inplace
- parses .m and saves the resulting pseudocode to
the file .p. This saves MATLAB from reparsing
.m the first time you call it. - MATLAB is very fast at parsing so the pcode
function rarely makes much of a speed difference. - One situation where pcode does provide a speed
benefit is for large GUI applications. - Another situation for pcode is when you want to
hide algorithms you've created in your M-file.
18Optimizing for Speed
Vectorizing CodeIt's best to avoid the use of
loops in programs that cannot benefit from
performance acceleration. Most loops can be
eliminated by performing an equivalent operation
using vectors instead. Coding Loops in a
MEX-File for SpeedIn this way, the loop executes
much more quickly since the instructions in the
loop do not have to be interpreted each time they
execute.
19Optimizing for Speed
- Preallocate to Improve PerformanceIt is much
faster to preallocate a block of memory large
enough to hold the matrix at its final size. For
example, using zeros() or ones(). - Functions Are Faster Than Scriptsso, use
function! - Using build-in function
- Measuring Execution Time with tic and toc tic
- run the program section to be timed
- toc
20Optimizing for Speed
- JIT(Just In Time) Accelerator
- MATLAB performance enhancements are
supported on a subset of MATLAB language
capability. - MATLAB accelerates code that uses the data types
that are shaded in the class hierarchy diagram
below
21Optimizing for Speed
- Performance acceleration applies to all MATLAB
array shapes except for arrays having more than
three dimensions. - for Loops execute faster in MATLAB as long as
- Indices of the loop are set to a range of scalar
values. - Code in loop uses only the supported data types
and array shapes. - If the code in the loop calls any functions,
they are built-in functions. - if, elseif, while, and switch statements
execute faster as long as the conditional
expression evaluates to a scalar value.
22 Profiler
- Profiler to help you improve the performance
of M-files.
23Inline function
g inline(expr) g inline(expr,arg1,arg2,...) Us
ing char, class, argnames to see the information
of g. vectorize(inline_fun), fun is an inline
function object. The result is the vectorized
version of the inline function.
24Function Handles
- A function handle is a MATLAB value that
provides a means of calling a function
indirectly. You can pass function handles in
calls to other functions or store function
handles in data structures for later use. - Constructing a Function Handle
- f_handle _at_functionname f_handle
str2func(functionname) Handles to Anonymous
Functions - sqr _at_(x) x.2 The variable sqr contains
a handle to this anonymous function. - Arrays of Function Handles
- trigFun _at_sin, _at_cos, _at_tan
trigFunstr2func(sin,cos,tan) - Calling a Function Using Its Handle
- f_handle()
- Evaluate function
- y1,feval(f_handles, arg1,)
y1,feval(funname, arg1,)
25Function Handles
Functions That Operate on Function Handles
26Function Handles
EXAMPLES