Beruflich Dokumente
Kultur Dokumente
Lab2FundamentalsofMATLAB
Headlines
MFiles
Operators
FlowControlStructures
Histogram
MFiles
TheMATLABsoftwareprovidesafullprogramminglanguagethatenablesyoutowriteaseries
ofMATLABstatementsintoafileandthenexecutethemwithasinglecommand.Youwriteyour
programinanordinarytextfile,givingthefileanameoffilename.m.
CreatingMFiles
Mfilesareordinarytextfilesthatyoucreateusingatexteditor.IfyouusetheMATLAB
Editor/Debugger,openanewfilebyselectingNew>MFilefromtheFilemenuatthetopofthe
MATLABCommandWindow.
TypesofMFiles
Scripts:
Areusefulforautomatingaseriesofstepsyouneedtoperformmanytimes.
Donotacceptinputargumentsorreturnoutputarguments.
StorevariablesinaworkspacethatissharedwithotherscriptsandwiththeMATLAB
commandlineinterface.
Functions:
AreusefulforextendingtheMATLABlanguageforyourapplication.
Canacceptinputargumentsandreturnoutputarguments.
Storevariablesinaworkspaceinternaltothefunction.
Exercise:
Writeafunctiontakeaimagenameasinputparameteranddisplaythenegativeofthisimage.
RelationalandLogicalOperators
Theseoperatorscompare(orperformlogicaloperationon)correspondingelementsofarraysof
equaldimensionselementbyelement,andproducealogicalarray.
Operator Name
& AND
| OR
~ NOT
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to
~= Not equal to
Page3
Exercise:
MatrixA=[
S S 7
2 S 8
ReturnAelementswhichare>4
SomeImportantVariablesandConstants
FlowControl
MATLABprovidestheconventionalflowcontrolstatementsneededinstructuredprogramming.
KeepinmindthatMATLABtreatsalogical1oranynonzeronumberastrue and0asfalse.
if,else,andelseif
if logical_expression1
statements1
elseif logical_expression2
statements2
else
statements3
end
Page4
for
for index = start:increment:end
statements
end
while
while expression
statements
end
switch,case,andotherwise
switch expression %(scalar or string)
case value1
statements1 % Executes if expression is value1
case {value2, value3,}
statements2 % Executes if expression is value2
otherwise
statements3 % Executes if expression does not
% match any case
end
VectorizingLoops
TheMATLABsoftwareusesamatrixlanguage,whichmeansitisdesignedforvectorandmatrix
operations.YoucanoftenspeedupyourMfilecodebyusingvectorizingalgorithmsthattake
advantageofthisdesign.Vectorizationmeansconvertingforandwhileloopstoequivalent
vectorormatrixoperations.SimpleExampleofVectorizingHereisonewaytocomputethesine
of10001valuesrangingfrom0to10:
imhist(f, b);
h = imhist(f, b); %Store histogram in h
Where:f isinputimage,
b isthenumberofbinsintheoutput(default256)
Exercise:
Howmanypixelshaveintensityintherange[0,32]incameraman.tif?