Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Lecture3
Lecture3
Matrixconcatenations
Usingthebracketswecancreatemoreandmorecomplicatedmatrixs:
>>[ones(2,2)zeros(2,2)]
>>[ones(2,2)zeros(2,2)]
Exercise
Createthematrixwhosefirstcolumnisthenumbers1:10,thenextcolumncontainsthe
first10squares1,4,9...100andthethirdcolumncontainsthefirst10powersof2:24
816...1024.
MoreExpressions
AllMatlabexpressionsaremadeoutofbasicbuildingblocksputtogether:
Constants
Variables
Operators
Keywords
Functions
Constants
Wehavemetsomeconstantsalready:1,3,1.56,5,pi.Buttherearemorethatwe
haven'tyetmet:i,j,(rootof1),2.4e12(2.4times10^12),'a'(thecharactera),
'hello'(avectorconsistingoftheletters'h','e','l','l','o').Notethatiand
jcanbeusedinawaydifferentfromvariables:youcanwrite3ior15j,butifyoudefine
a=10,writing4aisanerror...AlsonotethatMatlaballowusingthecolonnotationwith
letters:'a':'z'.
Notethatyoucanaccesslettersinastringjustelementsinanyothervector:
>>a='hello'
>>a(2)
>>a(4:5)='p!'
Exercise:
Createthestringofletters'zyx....cba'
Intertwinethetwostrings'Hello!!'and'Goodbye'(createthestring'HGeolold....!e')
Variables
http://ocw.mit.edu/ans7870/resources/farjoun/Lecture3.html
1/4
9/7/2015
Lecture3
Thereisn'tmuchtosayaboutvariables.Variablenamesmuststartwithaletter,andthe
variablenamelengthmustbenomorethan32characters.Namesmayuseletters,numbers
andtheunderscore'_'.
Notethatmatlabwillmakematrixsandvectorsgrowasneeded(fillingtheemptyspaceswith
zeros):
>>a=[1234]
>>a(5,5)=1
Operators
Wehavemetmanyoperators:=,+,,/,*,^,.,',[,],(,),,:.Thereareafew
others,asweshallseeshortly.
Keywords
Wehavenotyetseenmanykeywords...theonlyexceptionisend.
Functions
Wehaveseen:ones,zeros,diag,size,...Thereareothers.Forexample:sin,
cos,exp,log,sqrt.Youcanalsodefinenewfunctionsasweshalllearninthenext
lectureortwo.
Plotting
Let'slearnhowtomakenicepictures.plottingisoneofthebasictoolsofMatlab.Mostofthe
plottinghappensthroughplotanditsvariants.Bestistolearnbyexample:
>>x=0:0.01:1
>>y=sin(x)
>>plot(x,y)
Noticeseveralthings.
First,thesemicolon''attheendoftheexpressionsuppressestheoutputoftheresult.
However,itdoesnotinhibittheevaluationoftheexpression.Soxandyarestillasthey
wouldbeifthesemicolonwasmissingbutthescreenisblissfullyclean(tryitwithoutthe
semicolon).
Second,noticethattheplotfunctioncreatedanicefigureforus,withthefirst"wave"ofthe
sin.tryitputwithotherfunctions.
Exercise:
Plotthesinoveradifferentinterval
Plotamoresquiggilysinoverthesameinterval
plotthefunctionx^2betweenthenumbers5and5
plotthefunctionlog(x)from1to10(besurethatyourplotsarenice
http://ocw.mit.edu/ans7870/resources/farjoun/Lecture3.html
2/4
9/7/2015
Lecture3
andsmooth)
plotacircle(thinkparametricplot)
plotaLissajoucurve
Plota"heart"r=sin(theta/2)
Readmoreaboutplotanditsoptionalarguments!
Notethatusingplotwithonlyoneinputargumentdoessomethingalittlestrange(butusefulat
times...).
LogicalConstructs
Sometimesitisimportanttocomparenumbers.Forexamplewemightwanttoactdifferently
ifagivennumberispositiveornegative.Forthisweneedlogicaloperatorsandcomparisons.
Testing
First,comparisons.weusetheoperators==,~=,<>,<=,>=(the~keyisusuallyat
thetopleftofthekeyboard,anditneedstheSHIFTkey)tocomparenumberse.g:
>>1==2
>>3~=5
>>5<=6
>>7<=10
Noticethattheseexpressionsreturn0whentheyarefalseand1whenthearetrue.Thisisthe
convention.0isfalseand1istrue.
Whilethisnotationlookssimilartomath,thereareafewpitfalls
1<x<5doesNOTreturnwhatitdoesinmath...infactthiswillalwaybetrueregardless
ofthevalueofx.Canyouseewhy?
==isnot=.RegardlessofhowmanytimeIwillsaythis,peoplewillstillmakethis
mistakemanytimes...butperhapsbysayingitlots,itwillhappenless...maybe.
remember...youhavebeenwarned...=isassignment,and==isatestforequality.
Booleanoperations
Whatifwewanttochecktwothings?AandB?orperhapsAand(BorC)...forthisweneed
Booleanoperators:&(AND),|(OR),and~(NOT)
(The|isusuallyfoundatthemiddlerightofthekeyboard,anditneedsaSHIFTkey.)
1~=2|3<4
3~=4&8==(4+4)
~(2<=8)
http://ocw.mit.edu/ans7870/resources/farjoun/Lecture3.html
3/4
9/7/2015
Lecture3
FormattingText
Onceinawhilewewouldliketodisplaysometextthatisnicelyformattedandnotjustthe
outputasMatlabwantstodisplay.Todothisweusethesprintfcommand.
Initssimplestformitisquitestraightforward...thefirstarguemntisaformatstring,andthe
restareparametersforthestring.examples:
sprintf('hello,hereisanumber%d',17)
sprintf('mynameis%sandIam%gyearsold','Yossi',31)
Readuponsprintftogetthewholepicture.
http://ocw.mit.edu/ans7870/resources/farjoun/Lecture3.html
4/4