This document provides an overview of MATLAB orientation course on fundamentals of MATLAB programming delivered by Chirodeep Bakli. It discusses the different types of M-files (script and function M-files), how to create and call M-files, variables used in M-files (local, global, persistent variables), operators and functions that can be used in M-files. It provides examples of script and function M-files and demonstrates how to access text editors to create M-files, list files, check file contents and call functions.
MATLAB tutorial provided by Zabeel is comprehensive introduction to the MATLAB technical computing environment. The MATLAB class is intended for beginning users and those looking for a review. No prior programming experience or knowledge of MATLAB programming or MATLAB CODE is assumed. Themes of data analysis, visualization, modeling, and programming are explored throughout the course. Becoming a Certified MATLAB Associate is the first step in the MATLAB certification.
The frame work that I used for my Introduction to Matlab hour long course. Most of the instruction took place on a live Matlab screen, but this provided the framework
MATLAB tutorial provided by Zabeel is comprehensive introduction to the MATLAB technical computing environment. The MATLAB class is intended for beginning users and those looking for a review. No prior programming experience or knowledge of MATLAB programming or MATLAB CODE is assumed. Themes of data analysis, visualization, modeling, and programming are explored throughout the course. Becoming a Certified MATLAB Associate is the first step in the MATLAB certification.
The frame work that I used for my Introduction to Matlab hour long course. Most of the instruction took place on a live Matlab screen, but this provided the framework
Non-linear classification models rely commonly, on kernel functions. Models are highly dependent on a training (labeled) data sets. Models and therefore their underlying kernel have to adapt to the most recent labeled observations.
This presentation describes a solution to automated the evaluation and selection of a kernel function appropriate to a specific training set in online training.
MATLAB Script or programs are sequences of MATLAB commands saved in plain text files. When you type the name of the script file at the MATLAB prompt the commands in the script file are executed as if you had typed them in command window. Code for a script is done in an Editor window and saved as m-file.
In case your code has errors, MATLAB will show an error message in the command window, when you try to run the program .
Error message will be hyperlinked to the line in the file that caused the error.
This presentation describes some key features of Scala uses in the creation of machine learning algorithms:
1 Functorial definition of tensors for learning non-linear models (manifolds)
2. Monads to compose of explicit kernel functions in Euclidean space
3. Implicit class to extends Scala standard library
4. Stackable traits and dependency injection to build formal models and dynamic workflows
5. Tail recursion to implementation dynamic programming techniques
6. Streaming to reduce memory consumption for big data
7. Control of back pressure in data flows
http://patricknicolas.blogspot.com
http://bit.ly/12GjRu9
Non-linear classification models rely commonly, on kernel functions. Models are highly dependent on a training (labeled) data sets. Models and therefore their underlying kernel have to adapt to the most recent labeled observations.
This presentation describes a solution to automated the evaluation and selection of a kernel function appropriate to a specific training set in online training.
MATLAB Script or programs are sequences of MATLAB commands saved in plain text files. When you type the name of the script file at the MATLAB prompt the commands in the script file are executed as if you had typed them in command window. Code for a script is done in an Editor window and saved as m-file.
In case your code has errors, MATLAB will show an error message in the command window, when you try to run the program .
Error message will be hyperlinked to the line in the file that caused the error.
This presentation describes some key features of Scala uses in the creation of machine learning algorithms:
1 Functorial definition of tensors for learning non-linear models (manifolds)
2. Monads to compose of explicit kernel functions in Euclidean space
3. Implicit class to extends Scala standard library
4. Stackable traits and dependency injection to build formal models and dynamic workflows
5. Tail recursion to implementation dynamic programming techniques
6. Streaming to reduce memory consumption for big data
7. Control of back pressure in data flows
http://patricknicolas.blogspot.com
http://bit.ly/12GjRu9
What is Artificial Intelligence | Artificial Intelligence Tutorial For Beginn...Edureka!
** Machine Learning Engineer Masters Program: https://www.edureka.co/masters-program/machine-learning-engineer-training **
This tutorial on Artificial Intelligence gives you a brief introduction to AI discussing how it can be a threat as well as useful. This tutorial covers the following topics:
1. AI as a threat
2. What is AI?
3. History of AI
4. Machine Learning & Deep Learning examples
5. Dependency on AI
6.Applications of AI
7. AI Course at Edureka - https://goo.gl/VWNeAu
For more information, please write back to us at sales@edureka.co
Call us at IN: 9606058406 / US: 18338555775
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
MATLAB stands for Matrix Laboratory. MATLAB was written originally
to provide easy access to matrix software developed by the LINPACK (linear system package) and matlab 2012a manual pdf
Matlab is programming language developed by MathWorks that provides a computing environment for programming.
www.techsparks.co.in/introduction-and-basics-of-matlab/
This is an introduction to MATLAB. It was prepared for 4th grade students at university of Khartoum - surveying engineering department - along with the geometrical geodesy course.
MATLAB sessions: Laboratory 1
MAT 275 Laboratory 1
Introduction to MATLAB
MATLAB is a computer software commonly used in both education and industry to solve a wide range
of problems.
This Laboratory provides a brief introduction to MATLAB, and the tools and functions that help
you to work with MATLAB variables and files.
The MATLAB Environment
⋆ To start MATLAB double-click on the MATLAB shortcut icon. The MATLAB desktop will open.
On the left side you will generally find the Current Folder window and on the right the Workspace
and Command History windows. The Command Window is where the MATLAB commands are entered
and executed. Note that windows within the MATLAB desktop can be resized by dragging the separator
bar(s).
If you have never used MATLAB before, we suggest you type demo at the MATLAB prompt. Click
on Getting Started with MATLAB and run the file.
Basics And Help
Commands are entered in the Command Window.
⋆ Basic operations are +, -, *, and /. The sequence
>> a=2; b=3; a+b, a*b
ans =
5
ans =
6
defines variables a and b and assigns values 2 and 3, respectively, then computes the sum a+b and product
ab. Each command ends with , (output is visible) or ; (output is suppressed). The last command on a
line does not require a ,.
⋆ Standard functions can be invoked using their usual mathematical notations. For example
>> theta=pi/5;
>> cos(theta)^2+sin(theta)^2
ans =
1
verifies the trigonometric identity sin2 θ + cos2 θ = 1 for θ = π
5
. A list of elementary math functions can
be obtained by typing
>> help elfun
⋆ To obtain a description of the use of a particular function type help followed by the name of the
function. For example
>> help cosh
gives help on the hyperbolic cosine function.
⋆ To get a list of other groups of MATLAB programs already available enter help:
>> help
c⃝2011 Stefania Tracogna, SoMSS, ASU
MATLAB sessions: Laboratory 1
⋆ Another way to obtain help is through the desktop Help menu, Help > Product Help.
⋆ MATLAB is case-sensitive. For example
>> theta=1e-3, Theta=2e-5, ratio=theta/Theta
theta =
1.0000e-003
Theta =
2.0000e-005
ratio =
50
⋆ The quantities Inf (∞) and NaN (Not a Number) also appear frequently. Compare
>> c=1/0
c =
Inf
with
>> d=0/0
d =
NaN
Plotting with MATLAB
⋆ To plot a function you have to create two arrays (vectors): one containing the abscissae, the other the
corresponding function values. Both arrays should have the same length. For example, consider plotting
the function
y = f(x) =
x2 − sin(πx) + ex
x − 1
for 0 ≤ x ≤ 2. First choose a sample of x values in this interval:
>> x=[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1, ...
1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2]
x =
Columns 1 through 7
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000
Columns 8 through 14
0.7000 0.8000 0.9000 1.0000 1.1000 1.2000 1.3000
Columns 15 through 21
1.4000 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000
Note that an ellipsis ... was used to continue a command too long to fit in a sing ...
Similar to Fundamentals of matlab programming (20)
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
Democratizing Fuzzing at Scale by Abhishek Aryaabh.arya
Presented at NUS: Fuzzing and Software Security Summer School 2024
This keynote talks about the democratization of fuzzing at scale, highlighting the collaboration between open source communities, academia, and industry to advance the field of fuzzing. It delves into the history of fuzzing, the development of scalable fuzzing platforms, and the empowerment of community-driven research. The talk will further discuss recent advancements leveraging AI/ML and offer insights into the future evolution of the fuzzing landscape.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
Maintaining high-quality standards in the production of TMT bars is crucial for ensuring structural integrity in construction. Addressing common defects through careful monitoring, standardized processes, and advanced technology can significantly improve the quality of TMT bars. Continuous training and adherence to quality control measures will also play a pivotal role in minimizing these defects.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Automobile Management System Project Report.pdfKamal Acharya
The proposed project is developed to manage the automobile in the automobile dealer company. The main module in this project is login, automobile management, customer management, sales, complaints and reports. The first module is the login. The automobile showroom owner should login to the project for usage. The username and password are verified and if it is correct, next form opens. If the username and password are not correct, it shows the error message.
When a customer search for a automobile, if the automobile is available, they will be taken to a page that shows the details of the automobile including automobile name, automobile ID, quantity, price etc. “Automobile Management System” is useful for maintaining automobiles, customers effectively and hence helps for establishing good relation between customer and automobile organization. It contains various customized modules for effectively maintaining automobiles and stock information accurately and safely.
When the automobile is sold to the customer, stock will be reduced automatically. When a new purchase is made, stock will be increased automatically. While selecting automobiles for sale, the proposed software will automatically check for total number of available stock of that particular item, if the total stock of that particular item is less than 5, software will notify the user to purchase the particular item.
Also when the user tries to sale items which are not in stock, the system will prompt the user that the stock is not enough. Customers of this system can search for a automobile; can purchase a automobile easily by selecting fast. On the other hand the stock of automobiles can be maintained perfectly by the automobile shop manager overcoming the drawbacks of existing system.
1. MATLAB orientation courseMATLAB orientation course
Fundamentals ofFundamentals of
MATLAB ProgrammingMATLAB Programming
Delivered byDelivered by
Chirodeep BakliChirodeep Bakli
Research ScholarResearch Scholar
Indian Institute of Technology, KharagpurIndian Institute of Technology, Kharagpur
2. MATLAB orientation courseMATLAB orientation course
The m fileThe m file
Write a series of MATLAB statements into aWrite a series of MATLAB statements into a
file and then execute them with a singlefile and then execute them with a single
command.command.
Write your program in an ordinary text editorWrite 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 filenamefilename.m. The term you use for filename
becomes the new command that MATLABbecomes the new command that MATLAB
associates with the program. The fileassociates with the program. The file
extension of .m makes this a MATLAB M-file.extension of .m makes this a MATLAB M-file.
3. MATLAB orientation courseMATLAB orientation course
Script M-FilesScript M-Files Function M-FilesFunction M-Files
Do not accept inputDo not accept input
arguments or returnarguments or return
output argumentsoutput arguments
Can accept inputCan accept input
arguments and returnarguments and return
output argumentsoutput arguments
Operate on data in theOperate on data in the
workspaceworkspace
Internal variables areInternal variables are
local to the function bylocal to the function by
defaultdefault
Useful for automating aUseful for automating a
series of steps you needseries of steps you need
to perform many timesto perform many times
Useful for extending theUseful for extending the
MATLAB language forMATLAB language for
your applicationyour application
Kinds of M filesKinds of M files
4. MATLAB orientation courseMATLAB orientation course
An example of a script m-fileAn example of a script m-file
Factorial.mFactorial.m
n=10;n=10;
factorial=1;factorial=1;
forfor i=1:1:ni=1:1:n
factorial=factorial*i;factorial=factorial*i;
endend
5. MATLAB orientation courseMATLAB orientation course
An example of a function m-fileAn example of a function m-file
CommentComment
defines thedefines the
function name,function name,
and the numberand the number
and order ofand order of
input and outputinput and output
parametersparameters
H1 stands for "help 1" line.H1 stands for "help 1" line.
MATLAB displays the H1MATLAB displays the H1
line for a function when youline for a function when you
useuse lookforlookfor or request helpor request help
on an entire directory.on an entire directory.
6. MATLAB orientation courseMATLAB orientation course
Creating M-Files: Accessing Text EditorsCreating M-Files: Accessing Text Editors
>> edit fact>> edit fact.m.m
7. 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)
8. 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)
9. MATLAB orientation courseMATLAB orientation course
Calling functionCalling function
Call the fact functionCall the fact function
>> fact(5)>> fact(5)
10. MATLAB orientation courseMATLAB orientation course
Some m-File FunctionsSome m-File Functions
FunctionFunction DescriptionDescription
runrun
Run script that is not on currentRun script that is not on current
pathpath
type filenametype filename
lists the contents of the file given alists 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 asEchoes the script file contents as
they are executedthey are executed
11. 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 withoutDisplays results without
printing variable namesprinting variable names
beepbeep Makes computer beepMakes computer beep
evaleval
Interpret strings containingInterpret strings containing
MATLAB expressionsMATLAB expressions
fevalfeval Evaluate functionEvaluate function
12. MATLAB orientation courseMATLAB orientation course
Some m-File FunctionsSome m-File Functions
FunctionFunction DescriptionDescription
pausepause
pause (n)pause (n)
Pauses and waits until user pressesPauses and waits until user presses
any keyboard key.any keyboard key.
Pause (n) pauses for n seconds andPause (n) pauses for n seconds and
then continuesthen continues
waitforbuttonpresswaitforbuttonpress
Pauses until user presses mousePauses 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 byThe keyboard mode is terminated by
executing the commandexecuting the command RETURNRETURN
DBQUITDBQUIT can also be used to get outcan also be used to get out
of keyboard mode but in this case theof keyboard mode but in this case the
invoking M-file is terminated.invoking M-file is terminated.
13. MATLAB orientation courseMATLAB orientation course
VariablesVariables
The same guidelines that apply to MATLABThe same guidelines that apply to MATLAB
variables at the command line also apply tovariables at the command line also apply to
variables in M-files.variables in M-files.
No need to type or declare variables used inNo need to type or declare variables used in
M-files, (with the possible exception ofM-files, (with the possible exception of
designating them asdesignating them as globalglobal oror persistentpersistent).).
Before assigning one variable to another, youBefore 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.
14. MATLAB orientation courseMATLAB orientation course
Any operation that assigns a value to a variableAny operation that assigns a value to a variable
creates the variable, if needed, or overwrites itscreates 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 aMATLAB variable names must begin with a
letter, which may be followed by any combinationletter, which may be followed by any combination
of letters, digits, and underscores.of letters, digits, and underscores.
MATLAB distinguishes between uppercase andMATLAB distinguishes between uppercase and
lowercase characters, so A and a are not thelowercase characters, so A and a are not the
same variable.same variable.
Avoid Using Function Names for VariablesAvoid Using Function Names for Variables
VariablesVariables
15. 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 inVariables defined in a function do not remain in
memory from one function call to the next, unlessmemory from one function call to the next, unless
they are defined asthey are defined as globalglobal oror persistentpersistent..
Scripts, on the other hand, do not have a separateScripts, on the other hand, do not have a separate
workspace. They store their variables in aworkspace. They store their variables in a
workspace that is shared with the caller of theworkspace that is shared with the caller of the
script. When called from the command line, theyscript. When called from the command line, they
share the base workspace. When called from ashare the base workspace. When called from a
function, they share that function's workspace.function, they share that function's workspace.
Local VariablesLocal Variables
16. MATLAB orientation courseMATLAB orientation course
Global VariablesGlobal Variables
If several functions all declare a particular name asIf several functions all declare a particular name as
globalglobal, then they all share a single copy of that, then they all share a single copy of that
variable.variable.
Any assignment to that variable, in any function, isAny assignment to that variable, in any function, is
available to all the other functions declaring itavailable to all the other functions declaring it globalglobal..
Creating Global VariablesCreating Global Variables
Each function that uses a global variable must firstEach 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 commandTo access the variable from the MATLAB command
line, you must declare it as global at the commandline, you must declare it as global at the command
line.line.
17. 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 ALPHA
yp = [y-ALPHA*y];yp = [y-ALPHA*y];
Global VariablesGlobal Variables
Suppose, for example, you want to study the effectSuppose, 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.
18. MATLAB orientation courseMATLAB orientation course
Then in the commandThen in the command
prompt enter theprompt enter the
statementsstatements
global ALPHAglobal ALPHA
ALPHA = 0.01ALPHA = 0.01
y=myfunction(1:10);y=myfunction(1:10);
Global VariablesGlobal Variables
The global statement make the values assigned to ALPHA atThe global statement make the values assigned to ALPHA at
the command prompt available inside the function defined bythe command prompt available inside the function defined by
myfunction.m. They can be modified interactively and newmyfunction.m. They can be modified interactively and new
solutions obtained without editing any files.solutions obtained without editing any files.
19. MATLAB orientation courseMATLAB orientation course
Persistent VariablesPersistent Variables
Characteristics 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 whenMATLAB does not clear them from memory when
the function exits, so their value is retained fromthe 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 persistentYou must declare persistent variables as persistent
before you can use them in a function. It is usually bestbefore you can use them in a function. It is usually best
to put persistent declarations toward the beginning ofto put persistent declarations toward the beginning of
the function. You would declare persistent variable X asthe function. You would declare persistent variable X as
follows:follows:
>> persistent X>> persistent X
20. MATLAB orientation courseMATLAB orientation course
Special ValuesSpecial Values
ans:ans: Most recent answer (variable). If you doMost recent answer (variable). If you do
not assign an output variable to annot assign an output variable to an
expression, MATLAB automatically storesexpression, MATLAB automatically stores
the result in ans.the result in ans.
pi:pi: 3.1415926535897...3.1415926535897...
eps:eps: Machine epsilonMachine epsilon
inf:inf:Stands for infinityStands for infinity
NaN:NaN: Stands for Not-a-NumberStands for Not-a-Number
21. 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 threeThe MATLAB operators fall into three
categories:categories:
22. MATLAB orientation courseMATLAB orientation course
Arithmetic OperatorsArithmetic Operators
OperatorOperator DescriptionDescription
++ AdditionAddition
-- SubtractionSubtraction
.*.* MultiplicationMultiplication
././ Right divisionRight division
.. Left divisionLeft division
++ Unary plusUnary plus
23. 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
24. MATLAB orientation courseMATLAB orientation course
// Slash or matrix right division.Slash or matrix right division.
B/A is roughly the sameB/A is roughly the same
as B*inv(A). Moreas 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 withA./B is the matrix with
elements A(i,j)/B(i,j). Aelements A(i,j)/B(i,j). A
and B must have theand B must have the
same size, unless one ofsame size, unless one of
them is a scalar.them is a scalar.
Arithmetic OperatorsArithmetic Operators
25. MATLAB orientation courseMATLAB orientation course
Backslash or matrix leftBackslash or matrix left
division.division.
If A is a square matrix,If A is a square matrix,
AB is inv(A)*B.AB is inv(A)*B.
.. Array left division.Array left division.
A.B is the matrix withA.B is the matrix with
elements B(i,j)/A(i,j). Aelements B(i,j)/A(i,j). A
and B must have theand B must have the
same size, unless one ofsame size, unless one of
them is a scalar.them is a scalar.
Arithmetic OperatorsArithmetic Operators
26. 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
27. MATLAB orientation courseMATLAB orientation course
Logical OperatorsLogical Operators
MATLAB offers three types of logical operatorMATLAB 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.
28. MATLAB orientation courseMATLAB orientation course
Element-Wise Operators and FunctionsElement-Wise Operators and Functions
Perform element-wise logical operations onPerform element-wise logical operations on
their inputs to produce a like-sized outputtheir inputs to produce a like-sized output
array.array.
29. MATLAB orientation courseMATLAB orientation course
A and b must have equal dimensions, withA 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
30. MATLAB orientation courseMATLAB orientation course
Bit-Wise Operators and FunctionsBit-Wise Operators and Functions
Logically mask, invert, or shift the bits of an unsignedLogically mask, invert, or shift the bits of an unsigned
integer signalinteger signal
OperatioOperatio
nn
MaskMask
BitBit
InputInput
BitBit
OutputOutput
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
31. MATLAB orientation courseMATLAB orientation course
Perform AND and OR operations on logicalPerform AND and OR operations on logical
expressions containing scalar values.expressions containing scalar values.
They are short-circuit operators in that they onlyThey are short-circuit operators in that they only
evaluate their second operand when the result is notevaluate 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.
32. 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
33. MATLAB orientation courseMATLAB orientation course
Flow ControlFlow Control
ifif,, elseelse andand elseifelseif, executes a group of, executes a group of
statements based on some logicalstatements based on some logical
condition.condition.
switchswitch,, casecase andand otherwiseotherwise, executes, executes
different groups of statements dependingdifferent groups of statements depending
on the value of some logical condition.on the value of some logical condition.
whilewhile executes a group of statements anexecutes a group of statements an
indefinite number of times, based on someindefinite number of times, based on some
logical condition.logical condition.
34. MATLAB orientation courseMATLAB orientation course
forfor executes a group of statements a fixedexecutes a group of statements a fixed
number of times.number of times.
continuecontinue passes control to the next iterationpasses control to the next iteration
of aof a forfor oror whilewhile loop, skipping anyloop, skipping any
remaining statements in the body of theremaining statements in the body of the
loop.loop.
breakbreak terminates execution of aterminates execution of a forfor oror whilewhile
loop.loop.
returnreturn causes execution to return to thecauses execution to return to the
invoking function.invoking function.
All flow constructs useAll flow constructs use endend to indicate theto indicate the
end of the flow control block.end of the flow control block.
Flow ContrFlow Controlol
36. MATLAB orientation courseMATLAB orientation course
Unlike the C languageUnlike the C language
switch construct, theswitch construct, the
MATLABMATLAB switch does notswitch does not
"fall through.""fall through." That is, if theThat is, if the
first case statement is true,first case statement is true,
other case statements doother case statements do
not execute. Therefore,not execute. Therefore,
breakbreak statements are notstatements are not
used.used.
Flow ControlFlow Control
switch can handle multiple conditions in a single caseswitch 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
37. MATLAB orientation courseMATLAB orientation course
TheThe whilewhile loop executes a statement or group ofloop executes a statement or group of
statements repeatedly as long as the controllingstatements repeatedly as long as the controlling
expression is true (1).expression is true (1).
while expressionwhile expression
statementsstatements
endend
Exit aExit a whilewhile loop at any time using theloop at any time using the breakbreak
statement.statement.
Flow ControlFlow Control
ExampleExample
Infinite loopInfinite loop
While LoopsWhile Loops
38. MATLAB orientation courseMATLAB orientation course
TheThe forfor loop executes a statement or group of statementsloop 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
statementsstatements
endend
default increment is 1default increment is 1.You can specify any increment,.You can specify any increment,
including aincluding a negativenegative 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
39. 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);
endend
endend
Flow ControlFlow Control
For LoopsFor Loops
40. 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 vectorizingYou 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 toVectorization 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.
AA vectorized versionvectorized version of the same codeof the same code
is:is:
tictic
t = 0:.001:10;t = 0:.001:10;
y = sin(t);y = sin(t);
toctoc
tictic
i = 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);
endend
toc;toc;
41. MATLAB orientation courseMATLAB orientation course
File HandlingFile Handling
The most commonly used, high-level, file I/OThe most commonly used, high-level, file I/O
functions in MATLAB arefunctions in MATLAB are savesave andand loadload..
savesave
Saves workspace variables on disk.Saves workspace variables on disk.
As an alternative to the save function, selectAs an alternative to the save function, select
Save Workspace As from the File menu in theSave Workspace As from the File menu in the
MATLAB desktop, or use the WorkspaceMATLAB desktop, or use the Workspace
browser.browser.
42. MATLAB orientation courseMATLAB orientation course
SyntaxSyntax
• savesave
• save filenamesave filename
• save filename var1 var2 ...save filename var1 var2 ...
• save('filename', ...)save('filename', ...)
DescriptionDescription
• savesave by itself, stores all workspace variablesby itself, stores all workspace variables
in a binary format in the current directory inin a binary format in the current directory in
a file named matlab.mat. Retrieve the dataa file named matlab.mat. Retrieve the data
with load.with load.
File HandlingFile Handling
43. MATLAB orientation courseMATLAB orientation course
LoadLoad
Load workspace variables from diskLoad workspace variables from disk
SyntaxSyntax
•loadload
•load filenameload filename
•load filename X Y Zload filename X Y Z
DescriptionDescription
•loadload - 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'tmatlab.mat, if it exists, and returns an error if it doesn't
exist.exist.
•load filename X Y Zload filename X Y Z ... loads just the specified variables... loads just the specified variables
from the MAT-file. The wildcard '*' loads variables thatfrom the MAT-file. The wildcard '*' loads variables that
match a pattern (MAT-file only).match a pattern (MAT-file only).
File HandlingFile Handling
44. MATLAB orientation courseMATLAB orientation course
Read an ASCII delimited file into a matrixRead an ASCII delimited file into a matrix
Graphical InterfaceGraphical Interface
As an alternative to dlmread, use the ImportAs an alternative to dlmread, use the Import
Wizard. To activate the Import Wizard, selectWizard. To activate the Import Wizard, select
Import data from the File menu.Import data from the File menu.
SyntaxSyntax
M = 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