54
MATLAB orientation course: MATLAB orientation course: Organized by Organized by FOCUS – R&D FOCUS – R&D Matlab Programming Matlab Programming Delivered by Delivered by A. K. Bhattacharyya A. K. Bhattacharyya Senior Project Assistant Senior Project Assistant Department of Electrical Engineering Department of Electrical Engineering IIT Kharagpur IIT Kharagpur

Fundamentals Of Matlab Programming

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Matlab ProgrammingMatlab Programming

Delivered byDelivered by

A. K. BhattacharyyaA. K. BhattacharyyaSenior Project AssistantSenior Project Assistant

Department of Electrical EngineeringDepartment of Electrical EngineeringIIT KharagpurIIT Kharagpur

Page 2: Fundamentals Of  Matlab  Programming

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

Page 3: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

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

Kinds of M filesKinds of M files

Page 4: Fundamentals Of  Matlab  Programming

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

Page 5: Fundamentals Of  Matlab  Programming

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

Page 6: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Creating M-Files: Accessing Text Editors

• edit fact.m

Page 7: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Listing files

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

Page 8: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Checking file contentChecking file content

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

Page 9: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Calling function

• Call the fact function: fact(5)

Page 10: Fundamentals Of  Matlab  Programming

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

Page 11: Fundamentals Of  Matlab  Programming

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

Page 12: Fundamentals Of  Matlab  Programming

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

Page 13: Fundamentals Of  Matlab  Programming

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

Page 14: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

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

Page 15: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

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

Page 16: Fundamentals Of  Matlab  Programming

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

Page 17: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Global Variables

• Creating Global VariablesEach 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.

Page 18: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D 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];

Page 19: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Global VariablesThen in the command prompt enter the statements

global ALPHAALPHA = 0.01y=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.

Page 20: Fundamentals Of  Matlab  Programming

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

Page 21: Fundamentals Of  Matlab  Programming

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

Page 22: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Special ValuesSpecial 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...

Page 23: Fundamentals Of  Matlab  Programming

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

Page 24: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Arithmetic Operators

Operator Description

+ Addition

- Subtraction

.* Multiplication

./ Right division

.\ Left division

+ Unary plus

Page 25: Fundamentals Of  Matlab  Programming

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

Page 26: Fundamentals Of  Matlab  Programming

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

Page 27: Fundamentals Of  Matlab  Programming

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

Page 28: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Relational Operators

Operator Description

< Less than

<= Less than or equal to

> Greater than

Page 29: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Relational Operators

Operator Description

>= Greater than or equal to

== Equal to

~= Not equal to

Page 30: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

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.

Logical Operators

Page 31: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Element-Wise Operators and Functions

• Perform element-wise logical operations on their inputs to produce a like-sized output array.

Page 32: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Element-Wise Operators and Functions

A and b must have equal dimensions, with each dimension being the same size.

Page 33: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

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

Short-Circuit Operators

Page 34: Fundamentals Of  Matlab  Programming

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

Page 35: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Short-Circuit OperatorsExample:

if ((A==10)&&(B==20))

…..

end

if ((A==10)||(B==20))…..

end

Page 36: Fundamentals Of  Matlab  Programming

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

Page 37: Fundamentals Of  Matlab  Programming

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

Page 38: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Flow Control

Page 39: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Flow Control

Page 40: Fundamentals Of  Matlab  Programming

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

Page 41: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Flow Control

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

Page 42: Fundamentals Of  Matlab  Programming

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

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

Infinite loop

Page 43: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Flow ControlThe for loop executes a statement or group of statements a predetermined number of times.

for index = indexstart:increment:indexendstatements

enddefault 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);endYou 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); endend

Page 44: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Vectorizing LoopsMATLAB 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.tici = 0;for t = 0:.001:10 i = i+1; y(i) = sin(t);endtoc; t=tocA vectorized version of the same code is:tict = 0:.001:10;y = sin(t);toc

Page 45: Fundamentals Of  Matlab  Programming

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

Page 46: Fundamentals Of  Matlab  Programming

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

Page 47: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

File Handling

Load workspace variables from disk Syntax•load•load filename•load filename X Y Z

Page 48: Fundamentals Of  Matlab  Programming

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

Page 49: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D 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’)

Page 50: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

File Handling

Read an ASCII delimited file into a matrix Graphical InterfaceAs an alternative to dlmread, use the Import Wizard. To activate the Import Wizard, select Import data from the File menu. SyntaxM = dlmread(filename,delimiter)M = dlmread(filename,delimiter,R,C)M = dlmread(filename,delimiter,range)

Page 51: Fundamentals Of  Matlab  Programming

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

Page 52: Fundamentals Of  Matlab  Programming

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

Page 53: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

File Handling

Write a matrix to an ASCII delimited file Syntaxdlmwrite(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

Page 54: Fundamentals Of  Matlab  Programming

MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D

Thank YouThank You