Anda di halaman 1dari 54

Matlab Programming

Delivered by

A. K. Bhattacharyya
Senior Project Assistant
Department of Electrical Engineering
IIT Kharagpur

MATLAB orientation course: Organized by FOCUS R&D

The m file
Write a series of MATLAB statements into a file
and then execute them with a single command.

Write your program in an ordinary text editor


(Notepad), giving the file a name of filename.m.
The term you use for filename becomes the new
command that MATLAB associates with the
program. The file extension of .m makes this a
MATLAB M-file.
MATLAB orientation course: Organized by FOCUS R&D

Kinds of M files
Script M-Files

Function M-Files

Do not accept input arguments or


return output arguments

Can accept input arguments and


return output arguments

Operate on data in the workspace

Internal variables are local to the


function by default

Useful for automating a series of


steps you need to perform
many times

Useful for extending the MATLAB


language for your application

MATLAB orientation course: Organized by FOCUS R&D

An example of a script m-file


Factorial.m
n=10;
factorial=1;
for i=1:1:n
factorial=factorial*i;
end

MATLAB orientation course: Organized by FOCUS R&D

An example of a function m-file


Comment

defines the function


name, and the number
and order of input and
output parameters
H1 stands for "help 1" line.
MATLAB displays the H1
line for a function when you
use lookfor or request help
on an entire directory.
MATLAB orientation course: Organized by FOCUS R&D

Creating M-Files: Accessing Text Editors


edit fact.m

MATLAB orientation course: Organized by FOCUS R&D

Listing files
List the
names of
the files in
your
current
directory:
what

MATLAB orientation course: Organized by FOCUS R&D

Checking file content


List the contents of
M-file fact.m: type
fact

MATLAB orientation course: Organized by FOCUS R&D

Calling function
Call the fact function:
fact(5)

MATLAB orientation course: Organized by FOCUS R&D

Variables
The same guidelines that apply to
MATLAB variables at the command line
also apply to variables in M-files:
No need to type or declare variables used
in M-files, (with the possible exception of
designating them as global or persistent).

MATLAB orientation course: Organized by FOCUS R&D

Variables
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.
MATLAB orientation course: Organized by FOCUS R&D

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.
Avoid Using Function Names for Variables
MATLAB orientation course: Organized by FOCUS R&D

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.

MATLAB orientation course: Organized by FOCUS R&D

Local Variables
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.

MATLAB orientation course: Organized by FOCUS R&D

Local Variables
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.

MATLAB orientation course: Organized by FOCUS R&D

Global Variables
If several functions 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.

MATLAB orientation course: Organized by FOCUS R&D

Global Variables
Creating Global Variables
Each function that uses a global variable
must first declare the variable as global.
You would declare global variable
MAXLEN as follows:
global MAXLEN
To access the variable from the MATLAB
command line, you must declare it as
global at the command line.
MATLAB orientation course: Organized by FOCUS R&D

Global Variables

Suppose, for example, you want to


study the effect coefficients on a
equation. Create an M-file,
myfunction.m.
function yp = myfunction(y)
%The function you want to check.
global ALPHA
yp = [y-ALPHA*y];

MATLAB orientation course: Organized by FOCUS R&D

Global Variables
Then in the command prompt
enter the statements
global ALPHA
ALPHA = 0.01
y=myfunction(1:10);
The global statement make the
values assigned to ALPHA at the
command prompt available
inside the function defined by
myfunction.m. They can be
modified interactively and new
solutions obtained without editing
any files.
MATLAB orientation course: Organized by FOCUS R&D

Persistent Variables
Characteristics of persistent variables are:
1. You can only use them in functions.
2. Other functions are not allowed access
to them.
3. MATLAB does not clear them from
memory when the function exits, so their
value is retained from one function call to
the next.
MATLAB orientation course: Organized by FOCUS R&D

Persistent Variables
You must declare persistent variables as
persistent before you can use them in a function.
It is usually best to put persistent declarations
toward the beginning of the function. You would
declare persistent variable X as follows:
persistent X

MATLAB orientation course: Organized by FOCUS R&D

Special Values
ans: Most recent answer (variable). If
you do not assign an output variable
to an expression, MATLAB
automatically stores the result in ans.
pi: 3.1415926535897...

MATLAB orientation course: Organized by FOCUS R&D

Operators
The MATLAB operators fall into three
categories:
1. Arithmetic operators - perform
numeric computations
2. Relational operators - compare
operands quantitatively
3. Logical operators - use the logical
operators AND, OR
MATLAB orientation course: Organized by FOCUS R&D

Arithmetic Operators
Operator

Description

Addition

Subtraction

.*

Multiplication

./

Right division

.\

Left division

Unary plus

MATLAB orientation course: Organized by FOCUS R&D

Arithmetic Operators
Operator

Description

Unary minus

Colon operator

.^

Power

.'

Transpose

'

Complex conjugate transpose

Matrix multiplication

Matrix right division

Matrix left division

Matrix power

MATLAB orientation course: Organized by FOCUS R&D

Arithmetic Operators
/ Slash or matrix right division.
B/A is roughly the same
as B*inv(A). More
precisely, B/A = (A'\B')'.
./ Array right division.
A./B is the matrix with
elements A(i,j)/B(i,j). A
and B must have the
same size, unless one of
them is a scalar.
MATLAB orientation course: Organized by FOCUS R&D

Arithmetic Operators
\ Backslash or matrix left
division.
If A is a square matrix,
A\B is inv(A)*B.
.\ Array left division.
A.\B is the matrix with
elements B(i,j)/A(i,j). A
and B must have the
same size, unless one
of them is a scalar.

MATLAB orientation course: Organized by FOCUS R&D

Relational Operators
Operator

Description

<

Less than

<=

Less than or
equal to

>

Greater than

MATLAB orientation course: Organized by FOCUS R&D

Relational Operators
Operator

Description

>=

Greater than or
equal to

==

Equal to

~=

Not equal to

MATLAB orientation course: Organized by FOCUS R&D

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.
MATLAB orientation course: Organized by FOCUS R&D

Element-Wise Operators and Functions


Perform
element-wise
logical
operations on
their inputs to
produce a likesized output
array.
MATLAB orientation course: Organized by FOCUS R&D

Element-Wise Operators and Functions


A and b
must have
equal
dimensions
, with each
dimension
being the
same size.
MATLAB orientation course: Organized by FOCUS R&D

Short-Circuit 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.
MATLAB orientation course: Organized by FOCUS R&D

Short-Circuit Operators
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.

MATLAB orientation course: Organized by FOCUS R&D

Short-Circuit Operators
Example:
if ((A==10)&&(B==20))
..
end
if ((A==10)||(B==20))
..
end

MATLAB orientation course: Organized by FOCUS R&D

Flow Control
if, else and elseif, executes a group of
statements based on some logical condition.
switch, 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.

MATLAB orientation course: Organized by FOCUS R&D

Flow Control
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.
return causes execution to return to the invoking
function.
All flow constructs use end to indicate the end of the flow
control block.
MATLAB orientation course: Organized by FOCUS R&D

Flow Control

MATLAB orientation course: Organized by FOCUS R&D

Flow Control

MATLAB orientation course: Organized by FOCUS R&D

Flow Control

Unlike the C language switch construct, the MATLAB switch


does not "fall through." That is, if the first case statement is
true, other case statements do not execute. Therefore, break
statements are not used.
MATLAB orientation course: Organized by FOCUS R&D

Flow Control
switch can
handle multiple
conditions in a
single case
statement by
enclosing the
case
expression in a
cell array.

MATLAB orientation course: Organized by FOCUS R&D

Flow Control
The while loop executes a statement or group of
statements repeatedly as long as the controlling
expression is true (1).
while expression
statements
end
Infinite loop

Exit a while loop at any time using the break statement.

MATLAB orientation course: Organized by FOCUS R&D

Flow Control
The for loop executes a statement or group of statements a
predetermined number of times.
for index = indexstart:increment:indexend
statements
end
default increment is 1.You can specify any increment, including a
negative one.
x=[1,2,3,8,4];
for i = 2:6
x(i) = 2*x(i-1);
end
You can nest multiple for loops.
x=[1,2,3,8,4;4 9 7 10 15];
m=length(x(:,1));
n=length(x(1,:));
for i = 1:m
for j = 1:n
A(i,j) = 1/(i + j - 1);
end
end
MATLAB orientation course: Organized by FOCUS R&D

Vectorizing Loops
MATLAB is designed for vector and matrix operations.
You can often speed up your M-file code by using vectorizing algorithms
that take advantage of this design.
Vectorization means converting for and while loops to equivalent vector
or matrix operations.
Compute the sine of 1001 values ranging from 0 to 10.
tic
i = 0;
for t = 0:.001:10
i = i+1;
y(i) = sin(t);
end
toc; t=toc
A vectorized version of the same code is:
tic
t = 0:.001:10;
y = sin(t);
toc

MATLAB orientation course: Organized by FOCUS R&D

File Handling
The most commonly used, high-level,
file I/O functions in MATLAB are save
and load.
save
Saves workspace variables on disk.
As an alternative to the save function,
select Save Workspace As from the File
menu in the MATLAB desktop, or use the
Workspace browser.
MATLAB orientation course: Organized by FOCUS R&D

File Handling
Syntax
save
save filename
save filename var1 var2 ...
save('filename', ...)
Description
save by itself, stores all workspace variables in a
binary format in the current directory in a file
named matlab.mat. Retrieve the data with load.
MATLAB orientation course: Organized by FOCUS R&D

File Handling
Load workspace variables from disk
Syntax
load
load filename
load filename X Y Z

MATLAB orientation course: Organized by FOCUS R&D

File Handling
Description
load - loads all the variables from the MAT-file
matlab.mat, if it exists, and returns an error if it doesn't
exist.
load filename X Y Z ... loads just the specified variables
from the MAT-file. The wildcard '*' loads variables that
match a pattern (MAT-file only).

MATLAB orientation course: Organized by FOCUS R&D

File Handling
Use the functional form of load, such as
load('filename'), when the file name is
stored in a string, when an output
argument is requested, or if filename
contains spaces. To specify a command
line option with this functional form,
specify the option as a string argument,
including the hyphen.
For example, load('myfile.dat,-mat)
MATLAB orientation course: Organized by FOCUS R&D

File Handling
Read an ASCII delimited file into a matrix
Graphical Interface
As an alternative to dlmread, use the Import
Wizard. To activate the Import Wizard,
select Import data from the File menu.
Syntax
M = dlmread(filename,delimiter)
M = dlmread(filename,delimiter,R,C)
M = dlmread(filename,delimiter,range)
MATLAB orientation course: Organized by FOCUS R&D

File Handling

Description
M = dlmread(filename,delimiter) reads numeric data from the
ASCII delimited file filename, using the specified delimiter.
default delimiter - comma (,)
'\t - tab
M = dlmread(filename,delimiter,R,C) reads numeric data from
the ASCII delimited file filename, using the specified delimiter.
The values R and C specify the row and column where the
upper-left corner of the data lies in the file. R and C are zero
based so that R=0, C=0 specifies the first value in the file,
which is the upper left corner.

MATLAB orientation course: Organized by FOCUS R&D

File Handling
M = dlmread(filename,delimiter,range) reads the
range specified by range = [R1 C1 R2 C2] where
(R1,C1) is the upper-left corner of the data to be read
and (R2,C2) is the lower-right corner.
Remarks
dlmread fills empty delimited fields with zero. Data
files having lines that end with a non-space
delimiter, such as a semi-colon, produce a result that
has an additional last column of zeros.

MATLAB orientation course: Organized by FOCUS R&D

File Handling
Write a matrix to an ASCII delimited file Syntax
dlmwrite(filename,M,delimiter)
dlmwrite(filename,M,delimiter,R,C)
Description
dlmwrite(filename,M,delimiter) writes matrix M into an
ASCII-format file, using delimiter to separate matrix
elements.
default delimiter - comma (,)
'\t' tab delimiter

MATLAB orientation course: Organized by FOCUS R&D

Thank You

MATLAB orientation course: Organized by FOCUS R&D

Anda mungkin juga menyukai