Post on 22-Jan-2017
transcript
MATLAB orientation courseMATLAB orientation course
Fundamentals of Fundamentals of MATLAB ProgrammingMATLAB Programming
Delivered byDelivered byChirodeep BakliChirodeep Bakli
Research ScholarResearch ScholarIndian Institute of Technology, KharagpurIndian Institute of Technology, Kharagpur
MATLAB orientation courseMATLAB orientation course
The m fileThe m file
Write a series of MATLAB statements into a Write a series of MATLAB statements into a file and then execute them with a single file and then execute them with a single command.command.
Write your program in an ordinary text editor Write your program in an ordinary text editor (Notepad), giving the file a name of (Notepad), giving the file a name of filename.m. The term you use for filename filename.m. The term you use for filename becomes the new command that MATLAB becomes the new command that MATLAB associates with the program. The file associates with the program. The file extension of .m makes this a MATLAB M-file.extension of .m makes this a MATLAB M-file.
MATLAB orientation courseMATLAB orientation course
Script M-FilesScript M-Files Function M-FilesFunction M-Files
Do not accept input Do not accept input arguments or return arguments or return output argumentsoutput arguments
Can accept input Can accept input arguments and return arguments and return output argumentsoutput arguments
Operate on data in the Operate on data in the workspaceworkspace
Internal variables are Internal variables are local to the function by local to the function by defaultdefault
Useful for automating a Useful for automating a series of steps you need series of steps you need to perform many timesto perform many times
Useful for extending the Useful for extending the MATLAB language for MATLAB language for your applicationyour application
Kinds of M filesKinds of M files
MATLAB orientation courseMATLAB orientation course
An example of a script m-fileAn example of a script m-fileFactorial.mFactorial.mn=10;n=10;factorial=1;factorial=1;forfor i=1:1:n i=1:1:n factorial=factorial*i;factorial=factorial*i;endend
MATLAB orientation courseMATLAB orientation course
An example of a function m-fileAn example of a function m-file
CommentComment
defines the defines the function name, function name, and the number and the number and order of and order of input and output input and output parametersparameters
H1 stands for "help 1" line. H1 stands for "help 1" line. MATLAB displays the H1 MATLAB displays the H1 line for a function when you line for a function when you useuse lookforlookfor or request help or request help on an entire directory.on an entire directory.
MATLAB orientation courseMATLAB orientation course
Creating M-Files: Accessing Text EditorsCreating M-Files: Accessing Text Editors
>> edit fact>> edit fact.m.m
MATLAB orientation courseMATLAB orientation course
Listing filesListing files
>> what>> what (List the names of the files in your (List the names of the files in your current directory)current directory)
MATLAB orientation courseMATLAB orientation course
Checking file contentChecking file content
>> type fact>> type fact (List the contents of M-file fact.m) (List the contents of M-file fact.m)
MATLAB orientation courseMATLAB orientation course
Calling functionCalling function
Call the fact functionCall the fact function>> fact(5)>> fact(5)
MATLAB orientation courseMATLAB orientation course
Some m-File FunctionsSome m-File Functions
FunctionFunction DescriptionDescription
runrun Run script that is not on current Run script that is not on current pathpath
type filenametype filename lists the contents of the file given a lists the contents of the file given a full pathnamefull pathname
Edit funEdit fun opens the file fun.m in a text editoropens the file fun.m in a text editor
mfilenamemfilename Name of currently running M-fileName of currently running M-file
namelengthmaxnamelengthmax Return maximum identifier lengthReturn maximum identifier length
echoecho Echoes the script file contents as Echoes the script file contents as they are executedthey are executed
MATLAB orientation courseMATLAB orientation course
Some m-File FunctionsSome m-File Functions
FunctionFunction DescriptionDescription
inputinput Request user inputRequest user input
Disp (variablename)Disp (variablename) Displays results without Displays results without printing variable namesprinting variable names
beepbeep Makes computer beepMakes computer beep
evaleval Interpret strings containing Interpret strings containing MATLAB expressionsMATLAB expressions
fevalfeval Evaluate functionEvaluate function
MATLAB orientation courseMATLAB orientation course
Some m-File FunctionsSome m-File Functions
FunctionFunction DescriptionDescription
pausepausepause (n)pause (n)
Pauses and waits until user presses Pauses and waits until user presses any keyboard key.any keyboard key.Pause (n) pauses for n seconds and Pause (n) pauses for n seconds and then continuesthen continues
waitforbuttonpresswaitforbuttonpress Pauses until user presses mouse Pauses until user presses mouse button or any keyboard keybutton or any keyboard key
keyboardkeyboard
Temporarily gives control to keyboard.Temporarily gives control to keyboard.The keyboard mode is terminated by The keyboard mode is terminated by executing the commandexecuting the command RETURN RETURNDBQUIT DBQUIT can also be used to get out can also be used to get out of keyboard mode but in this case the of keyboard mode but in this case the invoking M-file is terminated.invoking M-file is terminated.
MATLAB orientation courseMATLAB orientation course
VariablesVariables
The same guidelines that apply to MATLAB The same guidelines that apply to MATLAB variables at the command line also apply to variables at the command line also apply to variables in M-files. variables in M-files.
No need to type or declare variables used in No need to type or declare variables used in M-files, (with the possible exception of M-files, (with the possible exception of designating them as designating them as globalglobal or or persistentpersistent).).
Before assigning one variable to another, you Before assigning one variable to another, you must be sure that the variable on the right-must be sure that the variable on the right-hand side of the assignment has a value.hand side of the assignment has a value.
MATLAB orientation courseMATLAB orientation course
Any operation that assigns a value to a variable Any operation that assigns a value to a variable creates the variable, if needed, or overwrites its creates the variable, if needed, or overwrites its current value, if it already exists.current value, if it already exists.
MATLAB variable names must begin with a MATLAB variable names must begin with a letter, which may be followed by any combination letter, which may be followed by any combination of letters, digits, and underscores.of letters, digits, and underscores.
MATLAB distinguishes between uppercase and MATLAB distinguishes between uppercase and lowercase characters, so A and a are not the lowercase characters, so A and a are not the same variable.same variable.
Avoid Using Function Names for VariablesAvoid Using Function Names for Variables
VariablesVariables
MATLAB orientation courseMATLAB orientation course
Each MATLAB function has its own local variables. Each MATLAB function has its own local variables. These are separate from those of other functions, These are separate from those of other functions, and from those of the base workspace. and from those of the base workspace.
Variables defined in a function do not remain in Variables defined in a function do not remain in memory from one function call to the next, unless memory from one function call to the next, unless they are defined as they are defined as globalglobal or or persistentpersistent. .
Scripts, on the other hand, do not have a separate Scripts, on the other hand, do not have a separate workspace. They store their variables in a workspace. They store their variables in a workspace that is shared with the caller of the workspace that is shared with the caller of the script. When called from the command line, they script. When called from the command line, they share the base workspace. When called from a share the base workspace. When called from a function, they share that function's workspace.function, they share that function's workspace.
Local VariablesLocal Variables
MATLAB orientation courseMATLAB orientation course
Global VariablesGlobal Variables If several functions all declare a particular name as If several functions all declare a particular name as
globalglobal, then they all share a single copy of that variable. , then they all share a single copy of that variable.
Any assignment to that variable, in any function, is Any assignment to that variable, in any function, is available to all the other functions declaring it available to all the other functions declaring it globalglobal. .
Creating Global VariablesCreating Global VariablesEach function that uses a global variable must first Each function that uses a global variable must first declare the variable as global. declare the variable as global. You would declare global variable MAXLEN as follows: You would declare global variable MAXLEN as follows: global MAXLENglobal MAXLEN
To access the variable from the MATLAB command line, To access the variable from the MATLAB command line, you must declare it as global at the command line.you must declare it as global at the command line.
MATLAB orientation courseMATLAB orientation course
function yp = myfunction(y)function yp = myfunction(y)%The function you want to check.%The function you want to check.global ALPHAglobal ALPHAyp = [y-ALPHA*y];yp = [y-ALPHA*y];
Global VariablesGlobal Variables
Suppose, for example, you want to study the effect Suppose, for example, you want to study the effect coefficients on a equation. Create an M-file, coefficients on a equation. Create an M-file, myfunction.m. myfunction.m.
MATLAB orientation courseMATLAB orientation course
Then in the command Then in the command prompt enter the prompt enter the statements statements
global ALPHAglobal ALPHAALPHA = 0.01ALPHA = 0.01y=myfunction(1:10);y=myfunction(1:10);
Global VariablesGlobal Variables
The global statement make the values assigned to ALPHA at The global statement make the values assigned to ALPHA at the command prompt available inside the function defined by the command prompt available inside the function defined by myfunction.m. They can be modified interactively and new myfunction.m. They can be modified interactively and new solutions obtained without editing any files.solutions obtained without editing any files.
MATLAB orientation courseMATLAB orientation course
Persistent VariablesPersistent VariablesCharacteristics of persistent variables are:Characteristics of persistent variables are:
1.1. You can only use them in functions.You can only use them in functions.
2.2. Other functions are not allowed access to them.Other functions are not allowed access to them.
3.3. MATLAB does not clear them from memory when MATLAB does not clear them from memory when the function exits, so their value is retained from the function exits, so their value is retained from one function call to the next.one function call to the next.
You must declare persistent variables as persistent You must declare persistent variables as persistent before you can use them in a function. It is usually best before you can use them in a function. It is usually best to put persistent declarations toward the beginning of to put persistent declarations toward the beginning of the function. You would declare persistent variable X as the function. You would declare persistent variable X as follows: follows:
>> persistent X>> persistent X
MATLAB orientation courseMATLAB orientation course
Special ValuesSpecial Values
ans:ans: Most recent answer (variable). If you do Most recent answer (variable). If you do not assign an output variable to an not assign an output variable to an expression, MATLAB automatically stores expression, MATLAB automatically stores the result in ans.the result in ans.
pi:pi: 3.1415926535897... 3.1415926535897...
eps:eps: Machine epsilon Machine epsilon
inf:inf:Stands for infinityStands for infinity
NaN:NaN: Stands for Not-a-Number Stands for Not-a-Number
MATLAB orientation courseMATLAB orientation course
OperatorsOperators
1.1. Arithmetic operatorsArithmetic operators - perform numeric - perform numeric computationscomputations
2.2. Relational operatorsRelational operators - compare operands - compare operands quantitativelyquantitatively
3.3. Logical operatorsLogical operators - use the logical - use the logical operators AND, ORoperators AND, OR
The MATLAB operators fall into three The MATLAB operators fall into three categories:categories:
MATLAB orientation courseMATLAB orientation course
Arithmetic OperatorsArithmetic OperatorsOperatorOperator DescriptionDescription
++ AdditionAddition
-- SubtractionSubtraction
.*.* MultiplicationMultiplication
././ Right divisionRight division
.\.\ Left divisionLeft division
++ Unary plusUnary plus
MATLAB orientation courseMATLAB orientation course
OperatorOperator DescriptionDescription-- Unary minusUnary minus:: Colon operatorColon operator.^.^ PowerPower.'.' TransposeTranspose'' Complex conjugate transposeComplex conjugate transpose** Matrix multiplicationMatrix multiplication// Matrix right divisionMatrix right division\\ Matrix left divisionMatrix left division^̂ Matrix powerMatrix power
Arithmetic OperatorsArithmetic Operators
MATLAB orientation courseMATLAB orientation course
// Slash or matrix right division. Slash or matrix right division. B/A is roughly the same B/A is roughly the same as B*inv(A). More as B*inv(A). More precisely, B/A = (A'\B')'.precisely, B/A = (A'\B')'.
././ Array right division. Array right division. A./B is the matrix with A./B is the matrix with elements A(i,j)/B(i,j). A elements A(i,j)/B(i,j). A and B must have the and B must have the same size, unless one of same size, unless one of them is a scalar.them is a scalar.
Arithmetic OperatorsArithmetic Operators
MATLAB orientation courseMATLAB orientation course
\\ Backslash or matrix left Backslash or matrix left division.division.If A is a square matrix, If A is a square matrix, A\B is inv(A)*B.A\B is inv(A)*B.
.\.\ Array left division. Array left division.A.\B is the matrix with A.\B is the matrix with elements B(i,j)/A(i,j). A elements B(i,j)/A(i,j). A and B must have the and B must have the same size, unless one of same size, unless one of them is a scalar. them is a scalar.
Arithmetic OperatorsArithmetic Operators
MATLAB orientation courseMATLAB orientation course
OperatorOperator DescriptionDescription
<< Less thanLess than
<=<= Less than or equal toLess than or equal to
>> Greater thanGreater than
>=>= Greater than or equal toGreater than or equal to
==== Equal toEqual to
~=~= Not equal toNot equal to
Relational OperatorsRelational Operators
MATLAB orientation courseMATLAB orientation course
Logical OperatorsLogical Operators
MATLAB offers three types of logical operator MATLAB offers three types of logical operator and functions.and functions.
Element-wiseElement-wise - operate on corresponding - operate on corresponding elements of logical arrays.elements of logical arrays.
Bit-wiseBit-wise - operate on corresponding bits - operate on corresponding bits of integer values or arrays.of integer values or arrays.
Short-circuitShort-circuit - operate on scalar, logical - operate on scalar, logical expressions.expressions.
MATLAB orientation courseMATLAB orientation course
Element-Wise Operators and FunctionsElement-Wise Operators and Functions
Perform element-wise logical operations on Perform element-wise logical operations on their inputs to produce a like-sized output their inputs to produce a like-sized output array.array.
MATLAB orientation courseMATLAB orientation course
A and b must have equal dimensions, with A and b must have equal dimensions, with each dimension being the same size.each dimension being the same size.
Element-Wise Operators and FunctionsElement-Wise Operators and Functions
MATLAB orientation courseMATLAB orientation course
Bit-Wise Operators and FunctionsBit-Wise Operators and FunctionsLogically mask, invert, or shift the bits of an unsigned Logically mask, invert, or shift the bits of an unsigned integer signalinteger signal
OperatioOperationn
Mask BitMask Bit Input Input BitBit
Output Output BitBit
ANDAND 11 11 11
11 00 00
00 11 00
00 00 00
OROR 11 11 11
00 11 11
11 00 11
00 00 00
XORXOR 11 11 00
11 00 11
00 11 11
00 00 00
MATLAB orientation courseMATLAB orientation course
Perform AND and OR operations on logical Perform AND and OR operations on logical expressions containing scalar values. expressions containing scalar values.
They are short-circuit operators in that they only They are short-circuit operators in that they only evaluate their second operand when the result is not evaluate their second operand when the result is not fully determined by the first operand.fully determined by the first operand.
Short-Circuit OperatorsShort-Circuit Operators
OperatorOperator DescriptionDescription
&&&& Returns true (1) if both inputs evaluate to true, Returns true (1) if both inputs evaluate to true, and false (0) if they do not.and false (0) if they do not.
|||| Returns true (1) if either input, or both, Returns true (1) if either input, or both, evaluate to true, and false (0) if they do not.evaluate to true, and false (0) if they do not.
MATLAB orientation courseMATLAB orientation course
Example:Example:
if ((A==10)&&(B==20))if ((A==10)&&(B==20))……....endend
if ((A==10)||(B==20))if ((A==10)||(B==20))……....endend
Short-Circuit OperatorsShort-Circuit Operators
MATLAB orientation courseMATLAB orientation course
Flow ControlFlow Control
ifif, , elseelse and and elseifelseif, executes a group of , executes a group of statements based on some logical statements based on some logical condition.condition.
switchswitch, , casecase and and otherwiseotherwise, executes , executes different groups of statements depending different groups of statements depending on the value of some logical condition.on the value of some logical condition.
whilewhile executes a group of statements an executes a group of statements an indefinite number of times, based on some indefinite number of times, based on some logical condition.logical condition.
MATLAB orientation courseMATLAB orientation course
forfor executes a group of statements a fixed executes a group of statements a fixed number of times.number of times.
continuecontinue passes control to the next iteration passes control to the next iteration of a of a forfor or or whilewhile loop, skipping any remaining loop, skipping any remaining statements in the body of the loop.statements in the body of the loop.
breakbreak terminates execution of a terminates execution of a forfor or or whilewhile loop.loop.
returnreturn causes execution to return to the causes execution to return to the invoking function.invoking function.
All flow constructs use All flow constructs use endend to indicate the to indicate the end of the flow control block.end of the flow control block.
Flow ContrFlow Controlol
MATLAB orientation courseMATLAB orientation course
Flow ControlFlow Control
If-else-end ConstructionsIf-else-end Constructionsmyfile.mmyfile.m
MATLAB orientation courseMATLAB orientation course
Unlike the C language Unlike the C language switch construct, the switch construct, the MATLAB MATLAB switch does not switch does not "fall through.""fall through." That is, if the That is, if the first case statement is true, first case statement is true, other case statements do other case statements do not execute. Therefore, not execute. Therefore, breakbreak statements are not statements are not used.used.
Flow ControlFlow Control
switch can handle multiple conditions in a single case switch can handle multiple conditions in a single case statement by enclosing the case expression in a cell array.statement by enclosing the case expression in a cell array.
myfile.mmyfile.mSwitch-Case ConstructionsSwitch-Case Constructions
MATLAB orientation courseMATLAB orientation course
The The whilewhile loop executes a statement or group of loop executes a statement or group of statements repeatedly as long as the controlling statements repeatedly as long as the controlling expression is true (1).expression is true (1).while expressionwhile expression
statementsstatementsendend
Exit a Exit a whilewhile loop at any time using the loop at any time using the breakbreak statement.statement.
Flow ControlFlow Control
ExampleExample
Infinite loopInfinite loop
While LoopsWhile Loops
MATLAB orientation courseMATLAB orientation course
The The forfor loop executes a statement or group of statements loop executes a statement or group of statements a predetermined number of times.a predetermined number of times.
for index = indexstart:increment:indexendfor index = indexstart:increment:indexend statementsstatementsendend
default increment is 1default increment is 1.You can specify any increment, .You can specify any increment, including a including a negative negative one. one.
x=[1,2,3,8,4];x=[1,2,3,8,4];for i = 2:6for i = 2:6 x(i) = 2*x(i-1);x(i) = 2*x(i-1);endend
Flow ControlFlow Control
For LoopsFor Loops
MATLAB orientation courseMATLAB orientation course
You can nest multiple for loops.You can nest multiple for loops.
x=[1,2,3,8,4;4 9 7 10 15];x=[1,2,3,8,4;4 9 7 10 15];m=length(x(:,1));m=length(x(:,1));n=length(x(1,:));n=length(x(1,:));for i = 1:mfor i = 1:m for j = 1:nfor j = 1:n A(i,j) = 1/(i + j - 1);A(i,j) = 1/(i + j - 1); endendendend
Flow ControlFlow Control
For LoopsFor Loops
MATLAB orientation courseMATLAB orientation course
Vectorizing LoopsVectorizing Loops MATLAB is designed for vector and matrix operations.MATLAB is designed for vector and matrix operations. You can often speed up your M-file code by using vectorizing You can often speed up your M-file code by using vectorizing algorithms that take advantage of this design. algorithms that take advantage of this design. Vectorization means converting for and while loops to Vectorization means converting for and while loops to equivalent vector or matrix operations.equivalent vector or matrix operations.
Compute the sine of 1001 values ranging from 0 to 10.Compute the sine of 1001 values ranging from 0 to 10.
A A vectorized versionvectorized version of the same code of the same code is:is:tictict = 0:.001:10;t = 0:.001:10;y = sin(t);y = sin(t);toctoc
tictici = 0;i = 0;for t = 0:.001:10for t = 0:.001:10 i = i+1;i = i+1; y(i) = sin(t);y(i) = sin(t);endendtoc;toc;
MATLAB orientation courseMATLAB orientation course
File HandlingFile Handling
The most commonly used, high-level, file I/O The most commonly used, high-level, file I/O functions in MATLAB are functions in MATLAB are savesave and and loadload. .
savesave Saves workspace variables on disk. Saves workspace variables on disk.
As an alternative to the save function, select As an alternative to the save function, select Save Workspace As from the File menu in the Save Workspace As from the File menu in the MATLAB desktop, or use the Workspace MATLAB desktop, or use the Workspace browser.browser.
MATLAB orientation courseMATLAB orientation course
Syntax Syntax • savesave• save filenamesave filename• save filename var1 var2 ...save filename var1 var2 ...• save('filename', ...)save('filename', ...)
DescriptionDescription• savesave by itself, stores all workspace variables by itself, stores all workspace variables
in a binary format in the current directory in in a binary format in the current directory in a file named matlab.mat. Retrieve the data a file named matlab.mat. Retrieve the data with load. with load.
File HandlingFile Handling
MATLAB orientation courseMATLAB orientation course
LoadLoad Load workspace variables from disk Load workspace variables from disk
SyntaxSyntax•loadload•load filenameload filename•load filename X Y Zload filename X Y Z
DescriptionDescription•load load - loads all the variables from the MAT-file - loads all the variables from the MAT-file matlab.mat, if it exists, and returns an error if it doesn't matlab.mat, if it exists, and returns an error if it doesn't exist.exist. •load filename X Y Z load filename X Y Z ... loads just the specified variables ... loads just the specified variables from the MAT-file. The wildcard '*' loads variables that from the MAT-file. The wildcard '*' loads variables that match a pattern (MAT-file only).match a pattern (MAT-file only).
File HandlingFile Handling
MATLAB orientation courseMATLAB orientation course
Read an ASCII delimited file into a matrix Read an ASCII delimited file into a matrix Graphical InterfaceGraphical Interface
As an alternative to dlmread, use the Import As an alternative to dlmread, use the Import Wizard. To activate the Import Wizard, select Wizard. To activate the Import Wizard, select Import data from the File menu.Import data from the File menu.
SyntaxSyntaxM = dlmread(filename,delimiter)M = dlmread(filename,delimiter)M = dlmread(filename,delimiter,R,C)M = dlmread(filename,delimiter,R,C)M = dlmread(filename,delimiter,range)M = dlmread(filename,delimiter,range)
File HandlingFile Handling