Sei sulla pagina 1di 6

D. N.

Maywar, RIT vS2131 1

Writing,Executing,andSubmittingMATLABCode
Below are rules and recommendations for writing, executing, and submitting your MATLAB
code.

Rules:followtheserulestoreceivefullcreditonyourassignments:
o publishcodeforsubmission
o mfileheader
o cells
o inlinedescriptions
o unitsofquantities
o plotting

Recommendations:followtheserecommendationsifyoulike(doesnotimpactgrade):
o Saveasseparatemfiles
o MATLABvectorization
o Executing&Troubleshootingcode

I. Recommendation:Saveasseparatemfiles
MATLABcodeistypicallystoredinscriptfilescalledmfiles.Irecommendthatyoucreateanew
mfile for each assignment problem, instead of continuing to edit the same file for each
problem.Thismethodwillallowyoutokeepyourold,workingcodeandreadilyrunitagain,if
desired.Iftwoproblemassignmentsaresimilar,simplyopentheoldmfile,saveitasanewm
file, and begin editing the new file. At the end of our work together, you will likely have an
assortmentofmfiles.

II. Rule:publishcodeforsubmission
To prepare your code for submission, use the MATLAB publish command. There are two main
waystoinvokethepublishcommand:
1) TypethepublishcommandintheMATLABCommandwindow,usingthenameofthem
filenameandthedesiredoutputfileformatasthefunctionarguments:
>>publish(mfile_name.m,pdf)
2) For recent versions of MATLAB, there is a PUBLISH menu as part of the MATLAB
Editor.Themenussettingsallowyoutochoosetheoutputfileformat.
Usingeithermethod,publishyourmfileasapdffileandthenprintthepdffileforsubmission.

Thepublishedcodefileprovidesseveraladvantages:
Usesthefirstcellnametocreateatitle
UsestheremainingcellnamestocreateaTableofContents
Usescellnamestocreatesectionswithinthepublisheddocument
Generatesplotsandplaceseachplotwhereitisgeneratedinthecode

D. N. Maywar, RIT vS2131 2

III. Rule:mfileheader
Createaheaderatthetopofyourmfiletoprovideadescriptionofyourmfile.

Forhomeworkassignments,createaheaderwiththefollowinginformation:
%%HW# Pr obl em#: br i ef descr i pt i on of pr obl em
%cour se number , cour se name
%Semest er i nf o
%TeamMember names

Anexamplehomeworkheaderis:
%%HW2 Pr obl em12: Tempor al Phase phi ( t )
%TCET- 740, Fi ber - Opt i cs Tel ecommuni cat i ons Technol ogy
%Fal l Semest er S2131
%Cl audi o I ppol i t o & J ose Bet ances, TeamRocket

Forreportsonjournalpapers,createaheaderthatincludesthefollowinginformation:
%%Descr i pt i on of si mul at i ons
%Paper aut hor s, paper t i t l e, J our nal name, vol ume number , page number
r ange ##- - ##, year of publ i cat i on.
%TeamMember names



IV. Rule:Cells
CellsarejustsectionsofMATLABcode.Tocreateacell,usetwopercentsignsinsuccession,like
this:
%%Name of cel l
The name of the cell is written in the same line as the two percent signs %%. Note that the
headerdiscussedaboveisjustthefirstcellinthemfile.

Herearesomereasonstousecells:
Cellsmakeiteasiertoreadandthereforetroubleshootcode
Cellscanexecuted(run)independently,makingiteasiertotestcode
Cells are used by the MATLAB publish command to create formatted sections in the
publisheddocumentandtocreateaTableofContents

Use cell names that make sense to the problem at hand. Some examples of cell names used
previouslyare:
independentvariables
electricfield
temporalphaseexpression
plots

D. N. Maywar, RIT vS2131 3

V. Rule:Inlinedescriptions
Write an inline description for every quantity in your MATLAB code. These descriptions
improveclarity,readability,andtheeaseoftroubleshooting.Towriteaninlinedescription,use
onepercentsign(%)followedbythedescription,suchas:
A = 2; %ampl i t ude [ sqr t ( W) ]
w = 2 * pi * 200; %angul ar f r equency [ r ad- THz]
n = 1. 50; %r ef r act i ve i ndex [ - - ]
t ps = [ 1 : 1 : 100] ; %t i me vect or [ ps]
E = A * exp( 1i * w * t ) ; %el ect r i c f i el d [ sqr t ( W) ]

At the end of your description, include the units of the quantity. If the quantity doesnt have
any units, use []. The use of units helps in keeping track of units, especially when different
quantitiesarecombinedtogethertoformotherquantities.Theuseofunitsisdiscussedfurther
intherulebelow.


VI. Rule:Unitsofquantities
Inregardstounits,itisimportantto:
a) Thinkcarefullyabouttheunitsinyourcalculationssothatthenumericalvaluesdo
notapproachthenumericalnoiseofyourcomputer(inordertoavoidnumerical
noiseerrors)
b) Recordunitsinyourinlinedescriptions(inordertobeabletoeasilytrackthem
throughoutyourcodeandavoidmistakes)
Recordingunits(b)wasfirstdiscussedintheruleabove.
Letssayyouwanttocreateatimevectorwithvaluesfrom0to100picoseconds(where
apicosecond=1E12seconds).Onewaytocodethisvectorisasfollows:
t s = [ 0 : 0. 01E- 12 : 100E- 12] ; %t i me vect or , [ s]
Thevaluesincludedintheabovetimevectortsareaverynaturalwaytoprogramthevalues
correspond to the SI unit of seconds [s]. To emphasize the units, the programmer has placed
[s]asaninlinecomment.
The problem with the above time vector ts is that its values are verysmall. Computers
dontlikeverysmallnumbersbecausecomputershaveacomputationalnoiselimit.Ifthesizeof
the number is around (or less than) this noise limit, watch out! Your computer can generate
numericalnoisethatcanmessupyourcalculations.Letssayyourcomputerhasanoiselimitof
1E16; this number might seem small, but square any value of the above time vector, and the
squaredvaluehasfallenbelowthenoiselimit.
Oneconsequenceofnumericalnoiseisthateverynumberyoucalculateisactuallythat
number+numericalnoise.Fornumberssuchas2and20,theadditionofnumericalnoiseis
insignificant. However, the addition to numerical noise to the number 0 can be significant.
Thenumber0isnotreally0duringyourcalculationsitis0+noise.Keepthatinmind.
Backtothetimevectortthegoalistocreateatimevectorwhosevaluesvaryfrom0
to100picoseconds.Hereisabetterwaytocreatethatvector:
t ps = [ 0 : 0. 01 : 100] ; %t i me vect or , [ ps]
D. N. Maywar, RIT vS2131 4

The values included in the above time vector tps are written directly as picoseconds. To
emphasizetheunits,theprogrammerhasplaced[ps]asaninlinecomment.Peopleareoften
uncomfortable with this way to write number values because the values are no longer
(apparently)correspondingtotheSIunitofseconds[s].Theadvantage,however,isthatweno
longer have really small numerical values for the computer to use, and thus we are better
preparedtoavoidproblemswithnumericalnoise.
IfyouareuncomfortablenotusingSIunits,herearesomewordstowinyouover:with
onlyoneexception,MATLABdoesntknowunits!MATLABitselfdoesntassociateanyunitswith
anyofthefollowingvectors:
t s = [ 0 : 0. 01E- 12 : 100E- 12] ; %t i me vect or , [ s]
t ps = [ 0 : 0. 01 : 100] ; %t i me vect or , [ ps]
Instead, the units are only in the mind of the programmer. That is why it is good practice to
write an inline comment such as % [s] or % [ps] so that you (as a programmer) can
rememberwhattheassociatedunitsare.
The following vectors are two vectors whose units are different in the mind of the
programmer, but not to MATLAB (since MATLAB is not associating any units with these
vectors):
t s = [ 0 : 0. 01 : 100] ; %t i me vect or , [ s]
t ps = [ 0 : 0. 01 : 100] ; %t i me vect or , [ ps]
MATLABseestheabovetwovectorsasexactlythesame.Theprogrammerneedstotrackwhich
vectorcorrespondstosecondsandwhichtopicoseconds.
The one exception for MATLAB is when it is evaluating the argument of sines and
cosines and similar functions. MATLAB assumes the units of the arguments are radians (by
default).


D. N. Maywar, RIT vS2131 5

VII. Rule:Plotting
Graphs are an important means of communicating information and should be accurate and
clear: Imagine that you are working at a company and you are presenting your graph to your
boss.Betteryet,imaginethatyouareworkingatacompanyandyouarepreparingyourgraph
foryourbosstopresenttohis/herboss.

FollowtheseruleswhenpreparingxyplotsinMATLAB:
1. Useasufficientnumberofdatapoints(ifyouareallowedtoincreasethenumberofdata
points)tomakesmoothfunctionsappearsmooth.
2. If your number of data points is restricted in some way such that (for a single data trace)
thereis50orlesspoints,makesurethefollowingisvisibleforeachdatatrace:
a. Useamarkerofsomekindoneachdatapoint
b. Useastraightlinesegmenttoconnecteachneighboringpairofdatapoints
3. Makeatitleforthegraph,usingtheMATABfunctiontitle.
a. Forhomeworkproblems,usetheformat:HW#Problem#Description
b. In the description, consider stating the main parameter values that distinguish the
graphfromothergraphs(suchasdistanceandopticalsourceused).
4. Axes
a. Correctlyandclearlylabeleachaxiswithadescriptivewordorphrase
b. Makesuretheyaxislabelappearsalongthelefthandside
c. Makesurethexaxislabelappearsalongthebottomofthegraph
d. Correctly and clearly provide units as part of each axis label. If the quantity is
unitless,use[].
e. Never use numeric values such that an axis ismultiplied by an exponential, such as
10
6
. Exponential numbers are hard to read and also easy for readers to miss.
Instead,scaleyourunitssuchthatthesignificantdigitappearswithin3digitsofthe
decimal point. For example, use 0.01 [mW] instead of 0.00001 [W]. As another
example,use10[ns]insteadof10,000[ps].
f. Set the axis limits as directed (if directed); use the ylim and xlim MATLAB
functionstosetthelimitsoftheyandxaxes,respectively
g. Makesuretheticknumbersarelargeenoughtobelegible
h. Thenumbersalongthe xaxisshouldvaryfromlowestonthelefttohighestonthe
right
i. Thenumbersalongtheyaxisshouldvaryfromlowestonthebottomtohigheston
thetop
5. Singlegraphwithmultiplecurves
a. Labeleachcurveseparately
b. Asameansoflabeling,OKtouseKeyaslongascurvesaredistinguishableinsome
way(e.g.,differentcolors,differentlinetypes)
6. Usethegridonfunctiontoplaceagridonyourgraph

D. N. Maywar, RIT vS2131 6

VIII. Recommendation:MATLABvectorization
WhenprograminginMATLAB,vectorquantitiescanbecreatedusingthefollowingsyntax:
f = 10: 1: 90; %vect or
Thisexpressioncreatesavectorofpointswhosevaluesrangefrom10to90instepsof1.Note
thatthisexpressiondoesnotusealoop,asinthefollowing:
f or n = 10 t o 90
f ( n) = n; %vect or
end
InMATLAB,youcanoftenavoidloopstructures.

Onceavectoriscreated,itcanbeusedtocreatenewvectors.Thefollowingstatementsall
createnewvectorsusingthepreviouslycreatedvectorfandwithoutusingloops:
g = 2 * f ; %g vect or
h = f . ^2; %h vect or , wher e each el ement i s t he squar e of f
v1 = cos( f ) ; %cosi ne vect or

IX. Recommendation:Executing&TroubleshootingCode
a. MonitorthevariabledimensionsintheMATLABWorkspacetoseeifeachdimension
is as expected. In particular, row vectors loop like <1xN> and column vectors look
like<Nx1>.
b. Executeyourcodeonecellatatime
c. ReadandrespondtoerrorsthattheMATLABscriptwindowprovidesasyoutype
incode
d. Read and consider responding to warnings that the MATLAB script window
providesasyoutypeincode
e. The . Operator: Always pay attention to multiplication signs * , division signs
/, and exponent signs ^ and think through whether or not you should precede
each sign with the MATLAB . operator, which causes elementbyelement
operationoneachelementinanarrayormatrix.
f. Clearoutmemory:CreateaClearingmfilethatyouexecutebeforerunningyour
MATLABcode.Itcouldcontainthefollowing:
cl c; %cl ear s t he cont r ol wi ndow of ol d commands
cl ear al l ; %cl ear s al l var i abl e memor y, but not f i gur es
cl ose al l ; %cl oses al l f i gur e wi ndows
g. Inproblemswhereyoucalculatedphase,avoidphasealiasingbytrackingthephase
differenceandmakingsurethephasedifferencebetweenconsecutivepointsisless
thanpi.Trackthephasedifferenceusinganexpressionlike:
phi d=( phi t ( 1, 2) - phi t ( 1, 1) ) / pi ; %nor mal i zed phase di f f [ - - ]
h. Sanitycheck!!
i. Whenyouwanttowritetheimaginaryvaluedquantityiconsiderusing1i

Potrebbero piacerti anche