scilab beginners

33
Scilab Enterprises S.A.S 143 bis rue Yves Le Coz 78000 Versailles (France) www.scilabenterprises.com Scilab for very beginners

Upload: babilonia-truta

Post on 11-Aug-2015

79 views

Category:

Engineering


9 download

TRANSCRIPT

  1. 1. ScilabEnterprisesS.A.S-143bisrueYvesLeCoz-78000Versailles(France)-www.scilab-enterprises.com Scilabforverybeginners
  2. 2. Scilabforverybeginners-2/33 Thisdocumenthasbeenco-writtenbyScilabEnterprisesandChristineGomez,mathematicsteacheratLyceDescartes (DescartesHighSchool)inAntony,Hauts-de-Seine(France). 2013ScilabEnterprises.Allrightsreserved.
  3. 3. Scilabforverybeginners-3/33 Tableofcontent Introduction Aboutthisdocument4 InstallScilab4 Mailinglist4 Complementaryresources4 Chapter1BecomefamiliarwithScilab Thegeneralenvironmentandtheconsole5 Simplenumericalcalculations6 Themenubar7 Theeditor8 Thegraphicswindow9 Windowsmanagementandworkspacecustomization11 Chapter2-Programming Variables,assignmentanddisplay12 Loops16 Tests17 2and3Dplots18 Supplementsonmatricesandvectors23 Calculationaccuracy29 Solvingdifferentialequations30 Chapter3UsefulScilabfunctions Inanalysis32 Inprobabilityandstatistics32 Todisplayandplot33 Utilities33
  4. 4. Scilabforverybeginners-4/33 Introduction Aboutthisdocument Thepurposeofthisdocumentistoguideyoustepbystepinexploringthevariousbasicfeatures ofScilabforauserwhohasneverusednumericalcomputationsoftware.Thispresentationis voluntarilylimitedtotheessentialtoalloweasierhandlingofScilab. Computations,graphsandillustrationsaremadewithScilab5.4.0.Youcanreproduceallthose commandsfromthisversion. InstallScilab Scilab is numerical computation software that anybody can freely download. Available under Windows, Linux and Mac OS X, Scilab can be downloaded at the following address: http://www.scilab.org/ YoucanbenotifiedofnewreleasesofScilabsoftwarebysubscribingtoourchannelnotification atthefollowingaddress:http://lists.scilab.org/mailman/listinfo/release Mailinglist TofacilitatetheexchangebetweenScilabusers,dedicatedmailinglistsexist(listinFrench,listfor the education world, international list in English). The principle is simple: registrants can communicatewitheachotherbye-mail(questions,answers,sharingofdocuments,feedbacks...). Tobrowsetheavailablelistsandtosubscribe,gotothefollowingaddress: http://www.scilab.org/communities/user_zone/mailing_list Complementaryresources IfyouhaveanInternetconnection,weinviteyoutovisitScilabwebsitewhereyouwillfinda sectiondedicatedtotheuseofScilab(http://www.scilab.org/support/documentation),withlinks andrelevantdocumentswhichcanbefreelydownloadedandprinted.
  5. 5. Scilabforverybeginners-5/33 Chapter1BecomefamiliarwithScilab TheusefulworkspaceinScilabconsistsofseveralwindows: Theconsoleformakingcalculations, Theeditorforwritingprograms, Thegraphicswindowsfordisplayinggraphics, Theembeddedhelp. Thegeneralenvironmentandtheconsole After double-clicking the icon to launch Scilab, Scilab environment by default consists of the following docked windows console, files and variables browsers, command history (see Windowsmanagementandworkspacecustomization,page11): Intheconsoleaftertheprompt-->,justtypeacommandandpresstheEnterkey(Windows andLinux)orReturnkey(MacOSX)onthekeyboardtoobtainthecorrespondingresult. --> 57/4 ans = 14.25 --> (2+9)^5 ans = 161051. Itispossibletocomebackatanymomentwiththekeyboard'sarrowkeysorwiththe mouse.Theleftandrightkeysareusedtochangetheinstructionsandtheupanddownkeysare usedtocomebackonapreviouslyexecutedcommand. Mention Beforetheresult,ansis displayedforanswer.
  6. 6. Scilabforverybeginners-6/33 Simplenumericalcalculations All computations done with Scilab are numerical. Scilab performs computations with matrices (seechapter2,page23). Operationsarewrittenwith+foraddition,forsubtraction,*formultiplication,/ fordivision,^forexponents.Forexample: -->2+3.4 ans = 5.4 Thecaseissensitive.Itisthusnecessarytorespectuppercaseandlowercaseforthecalculations tobeperformedproperly.Forexample,withsqrtcommand(whichcalculatesthesquareroot): -->sqrt(9) ans = 3. while: -->SQRT(9) !--error 4 Undefined variable: SQRT Particularnumbers %eand%pirepresentrespectivelyeand: --> %e %e = 2.7182818 --> %pi %pi = 3.1415927 %irepresentstheiofcomplexesininputandisdisplayediinoutput: --> 2+3*%i ans = 2. + 3.i Fornotdisplayingtheresults Inaddingasemicolon;attheendofacommandline,thecalculationisdonebuttheresultis notdisplayed. -->(1+sqrt(5))/2; --> (1+sqrt(5))/2 ans = 1.618034
  7. 7. Scilabforverybeginners-7/33 Toremindthenameofafunction ThenamesofcommonlyusedfunctionsaresummarizedinChapter3ofthisdocument(page32). Forexample: --> exp(10)/factorial(10) ans = 0.0060699 Thetabkeyonthekeyboardcanbeusedtocompletethenameofafunctionoravariableby givingitsfirstfewletters. Forexample,aftertypingintheconsolethecommand: -->fact andthenpressingthetabkey,awindowisdisplayedwithallthefunctionsandvariablesnames beginning with fact, such as factorial and factor. Just double click on the required functionorselectitwiththemouseorwiththekeysandpressEnter(WindowsandLinux) orReturn(MacOSX)toinsertitinthecommandline. Themenubar Themenuslistedbelowareparticularlyuseful. Applications Thecommandhistoryallowsyoutofindallthecommandsfromprevioussessionstothe currentsession. Thevariablesbrowserallowsyoutofindallvariablespreviouslyusedduringthecurrent session. Edit Preferences(inScilabmenuunderMacOSX)allowsyoutosetandcustomizecolors,fontsand fontsizeintheconsoleandintheeditor,whichisveryusefulforscreenprojection. ClickingonClear Consoleclearstheentirecontentoftheconsole.Inthiscase,thecommand historyisstillavailableandcalculationsmadeduringthesessionremaininmemory.Commands thathavebeenerasedarestillavailablethroughthekeyboardsarrowkeys. Control Tointerruptarunningprogram,youcan: TypepauseintheprogramorclickonControl>Interruptinthemenubar(CtrlXunder WindowsandLinuxorCommandXunderMacOSX),iftheprogramisalreadyrunning. In all cases, the prompt --> will turn into -1->, then into -2->, if the operationisrepeated. Toreturntothetimepriortotheprograminterruption,typeresumeintheconsoleor clickonControl>Resume. To quit for good a calculation without any possibility of return, type abort in the consoleorclickonControl>Abortinthemenubar. Mention Allavailablefunctionsare alsolistedintheembedded helpbyclickinginthemenu baron?>ScilabHelp.
  8. 8. Scilabforverybeginners-8/33 Theeditor Typingdirectlyintotheconsolehastwodisadvantages:itisnotpossibletosavethecommands anditisnoteasytoeditmultiplelinesofinstruction.Theeditoristheappropriatetooltorun multipleinstructions. Openingtheeditor Toopentheeditorfromtheconsole,clickonthefirsticoninthetoolbar oronApplications >SciNotesinthemenubar. TheeditoropenswithadefaultfilenamedUntitled 1. Writingintheeditor Typingintheeditorislikeasinanywordprocessor. Inthetexteditor,openingandclosingparentheses,endloops,functionandtestcommandsare addedautomatically.However,thesefeaturescanbedisabledinOptions>Auto-completionon menu,inclickingonthetwobelowentriesenabledbydefault: (,[, if,function, Whileinprincipleeachinstructionshouldbeenteredonaseparateline,itispossibletotype multiplestatementsonasamelineseparatingeachstatementwithasemicolon;. Aspaceatthestartofthelinecalledindentationisautomaticwhenalooporatestisstarted. Inthefollowingexample,wecalculate10termsofthesequence( !)definedby: ! = 1 !!! = 2! 3 Mention -Commentsprecededwith//willnotbetakenintoaccountinthecalculations. -Tochangethefont,clickonOptions>Preferences. -Whenwritingaprogram,indentationisautomatic.Ifthisisnotthecase,clickonFormat>Correctindentationtorestoreit (CtrlIunderWindowsandLinuxorCommandIunderMacOSX).
  9. 9. Scilabforverybeginners-9/33 Saving AnyfilecanbesavedbyclickingonFile>Saveas. Theextension.sceattheendofafilenamewilllaunchautomaticallyScilabwhenopeningit (exceptunderLinuxandMacOSX). Copyingintotheconsole,executingaprogram InclickingonExecuteinthemenubar,threeoptionsareavailable: Executefilewithnoecho(CtrlShiftEunderWindowsandLinux,CmdShiftEunder MacOSX):thefileisexecutedwithoutwritingtheprogramintheconsole(savingthe filefirstismandatory). Executefilewithecho(CtrlLunderWindowsandLinux,CmdLunderMacOSX): rewritethefileintotheconsoleandexecutesit. Executeuntilthecaret,withecho(CtrlEunderWindowsandLinux,CmdEunder MacOSX):rewritetheselectionchosenwiththemouseintotheconsoleandexecutesit orexecutethefiledatauntilthecaretpositiondefinedbytheuser. Standardcopy/pastecanalsobeused. Thegraphicswindow Openingagraphicswindow A graphics window opens automatically when making any plot. It is possible to plot curves, surfaces,sequencesofpoints(seechapter2,page18). Toobtainanexampleofcurve,typeintheconsole: -->plot Mention -Toeraseapreviousplot, typeclf (clearfigure). -Toopenanothergraphics window,typescf;(set currentfigure). Ifseveralgraphicwindows areopen,youcanchoosein whichtheplotwillbedrawn bytypingscf(n);nforthe graphicswindownumber (mentionedonthetopleft).
  10. 10. Scilabforverybeginners-10/33 Modifyingaplot Themagnifyingglass allowszooming.Tozoomintwodimensions,clickonthetoolandwith the mouse create a rectangle which will constitute the new enlarged view. To zoom in three dimensions,clickonthetoolandcreateaparallelepipedwhichwillconstitutethenewenlarged view.Itisalsopossibletozoominusingthemousewheel.Toreturntotheinitialscreen,clickon theothermagnifyingglass . The icon enables rotation of the figure (particularly useful in 3-D) with right click actions whichareguidedbymessagesinthebottomofthegraphicswindow. For more precise modifications, click on Edit > Figure properties or Axes properties and let yourselvesbeguided(thisoptionisnotyetavailableunderMacOSX). Onlinehelp Toaccesstheonlinehelp,clickon?>ScilabHelpinthemenubar,ortypeintheconsole: -->help Togethelpwithanyfunction,typehelpintheconsolefollowedbythenameoftheappropriate function.Forexample: -->help sin displayshelpforsin(sine)function. Mention Examplesofusecanbe executedinScilaband editedinSciNotesinusing theassociatedbuttonsin theexampleframework.
  11. 11. Scilabforverybeginners-11/33 Windowsmanagementandworkspacecustomization As in the default Scilab environment, where the console, files and variables browsers and command history are all together docked windows, all other windows in Scilab can be repositioned in a single one. For example, the user can choose to position the editor in the defaultenvironmentofScilab. Todockawindowinanotherone,firstidentifythebluehorizontalbarunderWindows,orblack underMacOSXandLinux,atthetopofthewindowinthetoolbarcontainingaquestionmarkon theright. Under Windows and Linux, click on this bar with the left mouse button and, while maintainingtheclick,movethemousepointerinthedesiredwindow. UnderMacOSX,clickonthisbarandwhilemaintainingtheclick,moveitinthedesired window. Arectangleappearsindicatingthefuturepositioningofthewindow.Whenthepositionisthe oneyouwant,releasethemousebutton.Tocancelandbringoutthewindow,clickonthesmall arrowontherightofthesamebar.
  12. 12. Scilabforverybeginners-12/33 Chapter2-Programming Intheexamplesgiveninthisdocument,anylineprecededby-->isacommand,theother linesarethereturnsfromcommands(calculationresults,errormessages).Donotwrite--> in the editor. They are introduced here to make the distinction between command lines and calculationresultsasitisdisplayedintheconsoleaftercopying/pasting.Whenpresentedina table (without --> and no calculation result), the commands are depicted exactly as they shouldbetypedintheeditor. Variables,assignmentanddisplay Variables Scilabisnotacomputeralgebrasystem.Itcalculatesonlywithnumbers.Allcalculationsaredone with matrices, although this may go unnoticed. Even if the concept of matrices is unknown, vectorsandsequencesofnumberscanexplainit,astheyare,infact,matricesofdimension1n orn1andanumberisitselfamatrixofdimension11. Variables do not need to be declared in advance, but any variable must have a value. For example,obtainingthevalueofavariablewhichhasnotbeengivenavalueproducesanerror: -->a !--error 4 Undefined variable : a Ifavalueisassignedtothevariablea,thereisnolongeranerror: --> a=%pi/4 a = 0.7853982 --> a a = 0.7853982 Variablesmaytakeanynamethatisnotalreadydefinedbythesystem: --> Piby2=%pi/2 Piby2 = 1.5707963 Mention LiketheScilabfunctions,a variablenamemustnot haveaccentsorspecial characters.
  13. 13. Scilabforverybeginners-13/33 Theresultofacalculationthatisnotassignedtoavariableisautomaticallyassignedtothe variablecalledans: -->3*(4-2) ans = 6. -->ans ans = 6. Functions Functionsaretheeasiestandmostnaturalwaytomakecomputationsfromvariablesandfor obtainingresultsfromvariables. A function definition begins with function and ends with endfunction. For example, to converteuros(e)indollars(d)withanexchangerate(t),thedollarsfunctionisdefined.The variablesareeandtandtheimageisd. -->function d=dollars(e,t); d=e*t; endfunction -->dollars(200,1.4) ans = 280. Veryusuallynumericalfunctionsarefunctionsofonerealvariable.Forexample,twofunctionsf andgaredefinedusingthefollowingcommands: -->function y=f(x); y=36/(8+exp(-x)); endfunction -->function y=g(x); y=4*x/9+4; endfunction Thedefinedfunctionscanthenbeusedtocalculatevalues: --> f(10) ans = 4.4999745 --> g(12.5) ans = 9.5555556 Mention Thevariablesxandyare dummyvariables,their namescanbereusedwhen definingotherfunctionsor inScilab.
  14. 14. Scilabforverybeginners-14/33 Requestingtheassignmentofavariable Assignmentismadeeasilyusingthe=operator. Display Writing Typingthenameofavariabledisplaysitsvalue,exceptwhenthereis;attheendofthe commandline. Brackets Matrices are defined using square brackets (see page 23). As mentioned before, matrix computationisthebasisofcalculationsinScilab.Aspaceorcommaisusedtoseparatecolumns andsemicolonsareusedtoseparaterows. Todefineacolumnvectorandobtainacolumndisplay: -->v=[3;-2;5] v = 3. - 2. 5. Todefinearowvectorandobtainarowdisplay: -->v=[3,-2,5] v = 3. - 2. 5. Todefineamatrixandobtainatabulardisplay: -->m=[1 2 3;4 5 6;7 8 9] m = 1. 2. 3. 4. 5. 6. 7. 8. 9. Mention Thiscommandcanalsobe typedundertheform: v=[3 -2 5] Mention Thiscommandcanalsobe typedundertheform: m=[1,2,3;4,5,6;7,8,9]
  15. 15. Scilabforverybeginners-15/33 dispfunction dispmustalwaysbeusedwithparentheses. Withthevectorvpreviouslydefined: -->v(2) ans = - 2. -->disp(v(2)) - 2. Todisplayastring(usuallyasentence),putitbetweenquotes: -->disp("Bob won") Bob won Todisplayacombinationofwordsandvaluesusethestringcommandwhichconvertsvalues tocharacterstringsusinga+betweenthedifferentparts: -->d=500; -->disp("Bob won "+string(d)+" dollars") Bob won 500 dollars Ifthesentencecontainsansinglequote,thelatterneedstobedoubledinthestringtobe displayedproperly: -->disp("It''s fair") It's fair Loops Incrementation The : operator allows to define vectors of numbers whose coordinates are in arithmetic sequence.Wegive:.Itispossiblethatendingvalueis notreached.Ifthestepisnotmentioned,itsdefaultvalueis1. Forexample,todefinearowvectorofintegerswhichincrementsinstepsof1from3and10: -->3:10 ans = 3. 4. 5. 6. 7. 8. 9. 10. orwhichincrementsinstepsof2from1to10: -->1:2:10 ans = 1. 3. 5. 7. 9.
  16. 16. Scilabforverybeginners-16/33 orwhichdecreasesinstepsof4from20to2: -->u=20:-4:2 u = 20. 16. 12. 8. 4. For Theeasiestloopstructureforafixednumberofiterationsiswrittenwithfor end. Example:Calculationof20termsofasequencedefinedbyrecurrenceby: ! = 4 !!! = ! + 2 + 3 Algorithm ScilabEditor Put4inu(1) Fornfrom1to20 u(n+1)takesthevalueu(n)+2n+3 andu(n) Displaynandu(n) Endfor u(1)=4; for n=1:20 u(n+1)= u(n)+2*n+3; disp([n,u(n)]) end While Tostopaloopwhenagivengoalisreached,while endisused. IplantedaChristmastreein2005measuring1.20m.Itgrowsby30cmperyear.Idecidedtocut itwhenitexceeds7m.InwhatyearwillIcutthetree? Algorithm ScilabEditor Put1.2inh(h=treeheight) Put2005iny(y=year) WhilehX=[1,2,5]; Y=[5,3,5]; -->X==Y ans = F F T Totestiftwovectorsareequal,isequalisusedand~isequalisusediftheyaredifferent: -->isequal(X,Y) ans = F -->~isequal(X,Y) ans = T Ifthen Thebasicconditionalstatementsarethefollowing: if then else end, if then elseif then else end. if thenmustbewrittenonthesamelineandlikewisewithelseif then. Mention Becautiouswithcalculationaccuracy.Calculationsareapproachedand==willsometimesgivewrongresults(see Calculationaccuracy,page30).
  17. 18. Scilabforverybeginners-18/33 Example:Alicethrowsthreedice. Ifshegetsthree6sshewins$20, Ifshegetsthreeidenticalnumbersdifferentfrom6shewins$10, Ifshegetstwoidenticalnumbersshewins$5, Otherwiseshewinsnothing. SimulateatrialandcalculateAliceswinningsusingthefunctions: grand(seepage22), unique(D)whichkeepsonlyoncethevaluesthatappearsseveraltimesinD, length(unique(D))whichreturnsthesizeoftheobtainedvector,thatistosay1if threediceareequal,and2iftwodiceareequal. Algorithm ScilabEditor PutthethreevaluesinD IfAlicegetsthree6,then Alicewins20dollars Elseifshereceivesthreeidenticalvalues, then Alicewins10dollars Else,ifshereceivestwoidenticalvalues,then Alicewins5dollars Otherwise Alicewinsnothing Endif DisplayAlice'swinnings D=grand(1,3,"uin",1,6); if D==[6,6,6] then W=20; elseif length(unique(D))==1 then W=10; elseif length (unique(D))==2 then W=5; else W=0; end disp("Alice wins "+.. string(W)+ " dollars") 2-Dand3-Dplots plotcommandisusedtocreateplotsintheplane.Colorandappearancecanbespecifiedby puttingindicationsofcolorandpointsstylewithinquotes: Colors "b"=blue(bydefault),"k"=black,"r"=red,"g"=green,"c"=cyan,"m"=magenta, "y"=yellow,"w"=white. Pointstyles Joined(bydefault),or".","+","o","x","*". Otheroptionsareavailablewith:"s","d","v","".
  18. 19. Scilabforverybeginners-19/33 Basicplots Toplotapoint PlotthepointA(1;2)witharedpoint. ScilabEditor GraphicsWindow plot(1,2,".r") Toplotasegment Plotthesegment[AB]inblue(bydefault)withA(1;2)andB(3;5). ScilabEditor GraphicsWindow plot([1,3],[2,5]) Plotsofplanecurvesdefinedbyfunctionsy=f(x) Forafunction ()thevaluesofxarespecifiedusingthelinspace commandbywriting: x=linspace(a,b,n);inwhichaisthesmallestvalueofthevariable ,bthehighestvalue of ,andnthenumberofvaluescalculatedbetweenaandb. Donotforgetthe;sympbolotherwiseallnvaluesof willbedisplayed. Forexample,considertwofunctions and definedovertheinterval[-2;5]by: = (! + 2)!! ,and = sin ! !
  19. 20. Scilabforverybeginners-20/33 Withtheprogrambelow,weplotthecurvedefinedby,inbluebydefault: ScilabEditor GraphicsWindow function y=f(x) y=(x^2+2*x)*exp(-x) endfunction x=linspace(-2,5,50); plot(x,f) Byaddingtheprogrambelow,weobtaintheplotoftwocurves,thatoffinredandthatofgin green.Thepreviousplotwasclearedthroughtheclfcommand(clearfigure). ScilabEditor GraphicsWindow function y=g(x) y=sin(x/2) endfunction x=linspace(-2,5,50); clf plot(x,f,"r",x,g,"g") Plotsofsequencesofpoints Termsofasequence The most common case is to plot the sequences of points(, )after calculating the coordinates ()ofavector .plot(u,"*r")specifiesthestyleandcolorofthepointsin quotes:redandnon-connectedstars.Bydefault,pointsareplottedinblueandareconnected. ScilabEditor GraphicsWindow for n=1:50 u(n)=(-0.8)^n; end clf; plot(u,"*r")
  20. 21. Scilabforverybeginners-21/33 Bivariatestatisticaldata Bivariate statistical data are given in the form of two vectors: lets call them X and Y. plot(X,Y,"m' ans = 1. 4. 2. 5. 3. 23. Operations Theoperations*,/arematrixoperations.Tomakeelementwiseoperations,weneedto putadotbeforetheoperatingsign:.*,./. -->A=[1,2,3;4,5,6] A = 1. 2. 3. 4. 5. 6. -->B=[1;1;2]
  21. 25. Scilabforverybeginners-25/33 B = 1. 1. 2. -->A*B ans = 9. 21. Matrixmultiplication -->A*A !--error 10 Inconsistent multiplication. Dimensionsarenotconsistent -->A.*A ans = 1. 4. 9. 16. 25. 36. Elementwisemultiplication -->2*(A+2) ans = 6. 8. 10. 12. 14. 16. Theoperationisperformedoneachelement because2isanumber -->A/A ans = 1. 1.518D-16 3.795D-15 1. GivesthematrixXforwhichX*A=A Theexactresultis: 1.0 01. Forreasonsofcalculationaccuracy,theresultcan beslightlydifferentdependingonyourversionof Scilabandyouroperatingsystem(seecalculation accuracy,page29). -->A./A ans = 1. 1. 1. 1. 1. 1. Givesthematrixdividedelementwise Inthecaseofvectors: -->C=1:4 C = 1. 2. 3. 4. -->C*C !--error 10 Inconsistent multiplication. Dimensionsarenotconsistent
  22. 26. Scilabforverybeginners-26/33 -->C.*C ans = 1. 4. 9. 16. ItisalsopossibletowriteC^2because,for vectors,exponentsareinterpretedasanoperation elementwise.Thisisnotthecasewithmatrices. -->1/C ans = 0.0333333 0.0666667 0.1 0.1333333 Inthisparticularcasewithvectors,wefindthe vectorXforwhichC*X=1 -->(1)./C ans = 1. 0.5 0.3333333 0.25 Reverseelementwise Aspreviously,C^(-1)ispossible.The parenthesesaround1arenecessarysothatthe pointisnotconsideredasacommaaspartofthe number1.Itisalsopossibletowrite1 ./Cwith aspacebetween1and. Solvinglinearsystems Tosolvethelinearsystem AX=Y,inwhichAisasquarematrix,usethebackslash X=AY. Becautious,theoperationY/Awillgive(onlyifthedimensionsarecorrect)anotherresult,that istosaythematrixZforwhichZA=Y. Tosolvethesystem: 1 2 3 4 5 6 = 1 1 -->A=[1 2 3;4 5 6]; -->Y=[1;1]; -->X=AY X = - 0.5 0. 0.5 -->A*X ans = 1. 1.
  23. 27. Scilabforverybeginners-27/33 Someusefulfunctions Sort Thegsortfunctionisusedtosorttheelementsofavectorinascendingordescendingorder. -->v=[2,6,9,6,-4,0,2] v = 2. 6. 9. 6. - 4. 0. 2. --> gsort(v,"g","i") ans = - 4. 0. 2. 2. 6. 6. 9. --> gsort(v) ans = 9. 6. 6. 2. 2. 0. - 4. Length Thelengthfunctionreturnsthenumberofcoordinatesforavector.Thesizefunctionreturns thedimensions(rows,columns)foramatrix. -->U=[1:10] U = 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. -->length(U) ans = 10. -->m=[1 2 3;4 5 6]; -->size(U) ans = 2. 3.
  24. 28. Scilabforverybeginners-28/33 Sumandproduct Thesumandprodfunctionsrespectivelycalculatethesumandtheproductoftheirargument elements. -->U=[1:10]; -->sum(U) ans = 55. -->prod(U) ans = 3628800. Unique The unique function keeps only once the elements of a vector (even if they are repeated severaltimes)andsortstheminascendingorder. -->v=[2,6,9,6,-4,0,2] v = 2. 6. 9. 6. - 4. 0. 2. -->unique(v) ans = - 4. 0. 2. 6. 9. Find Thefindfunctionsearchesforelementsinavectororamatrixandreturnsavectorcontaining thecorrespondingindices. Tofindalltheelementsofthevector smallerthan5: -->w=[1,5,3,8,14,7,3,2,12,6]; find(ww=[1,5,3,8,14,7,3,2,12,6]; find(w==3) ans = 3. 7. Theresultingvector(3,7)indicatesthatelements !and !areequalto3. Accuracycomputation Computation Numbershaveanabsolutevaluebetweenabout2.210 -308 and1.810 +308 . Thenumber%epsequalsto2.220446049D-16givesthesmallestrelativeprecisionthatcan beobtainedincomputations,whichthereforegivesabout16decimaldigits. Example1:Computationofsin() -->sin(%pi) ans = 1.225D-16 The value of above is not 0, but it is considered as zero. Indeed, compared to the maximumvalueofthesinefunction(i.e.1),itisequalto0withavaluelessthan%eps. Example2:Testingifthetrianglewithsides ,1et2isaright-angledtriangle: -->a=sqrt(3) a = 1.7320508 -->b=1 b = 1. -->c=2 c = 2. -->a^2+b^2==c^2 ans = F Theprogramrespondsfalse becausethevalueofa^2+b^2isapproximate
  25. 30. Scilabforverybeginners-30/33 -->abs(a^2+b^2-c^2)abs(a^2+b^2-c^2)/c^2a^2 ans = 3. Herethereare7decimalplaces,andwedonotsee theerror. -->format(20) -->a^2 ans = 2.99999999999999956 Herethereare17decimalplaces,andwecansee theerror Solvingdifferentialequations Tofindthesolutionsofanexplicitsystemofdifferentialequations,simplyreducetodifferential equationsoforder1. ! = , ! = ! inwhich !and representtimeand !and ()arevectors, thenapplytheodefunction:y=ode(y0,t0,t,f),with: y0:initialcondition,vectorofdimension , t0:initialtime, t:vectorofdimensionTcorrespondingtothetimesinwhichthesolutioniscomputed. Thisvectormustbeginwitht0. f:functiondefiningthesystemundertheform: function yprim=f(t,y) yprim(1)=... yprim(2)=... .... yprim(n)=... endfunction
  26. 31. Scilabforverybeginners-31/33 Thesolutionyisamatrixofdimension : ! 1 ! 2 ! ! 1 ! 2 ! ! 1 ! 2 ! Example:Solvingthedifferentialequation " = = , ! = Thisequationoforder2isreducedtoasystemoftwoequationsoforder1asdefinedby: = (1) (2) = , = (1) (2) = " and 1 = 2 2 = 4(1) Comment ScilabEditor Wedefinethefunctionreturningoutputvectory frominputvariablestandy(yisavector). Wedefinethevaluesoftforplotting. (thesolverchoosesitselfthegoodvaluesoftfor theinternalcomputationofthesolution). Wedefinetheinitialconditions. Weexecuteode. Weplottheintegralcurveofywithrespecttot. function yprim=f(t,y) yprim(1)=y(2); yprim(2)=-4*y(1) ; endfunction t0=0; tmax=5; t=t0:0.05:tmax; y0=3; yprim0=0; y=ode([y0;yprim0],t0,t,f); clf; plot(t,y(1,:)) n T
  27. 32. Scilabforverybeginners-32/33 Chapter3UsefulScilabfunctions Analysis sqrt(x) returns the square root of with real positive or zero, and the complex rootofrealpositivepartotherwise. log(x)returnsthenaturallogarithmofxwithxrealorcomplexnumber. exp(x)returnstheexponentialof with realorcomplexnumber. abs(x)returnstheabsolutevalueof real(orthemoduleif iscomplex). int(x)returnsthetruncationof real(theintegerbeforethedecimal). floor(x)returnstheintegerpartof real(theinteger forwhich < + 1). ceil(x)for realreturnstheinteger forwhich 1 < . Probabilityandstatistics factorial(n)returnsthefactorialofnwithn positiveorzerointeger. grand(1,p,"uin",m,n) returns a vector of p random integer sequences taken betweenmandn with p positiveinteger,mandnintegersand . grand(1,p,"unf",a,b) returns a vector of p random real sequences taken betweenaandb with p positiveinteger,aandbrealand . sum(n)returnsthesumofthevaluesofvector (usedtocalculateatotal). cumsum(n) returns the vector of increasing cumulative values of vector (used to calculatetheincreasingcumulativenumbers). length(v)returnsthenumberofcoordinatesofvector . gsort(v)returnsthevectorofnumbersorstrings sortedindescendingorder. gsort(v,"g","i")returnsthevectorofnumbersorstrings sortedinascending order. mean(v)returnstheaverageofthevectorofnumbers . stdev(v)returnsthestandarddeviationofnumbers vector. bar(v,n,couleur)drawsthebargraphwith asX-coordinate, asY-coordinate, and beingsamesizelinevectors.Bydefault,bar(n)drawsthebargraphof in bluewith1,2,3asX-coordinates. bar(v,[n1,n2]) draws a double bar graph withas X-coordinate, n1 as Y- coordinateinblueandn2asY-coordinateingreen,with ,n1andn2beingsamesize linevectors. rand(n,p)with and positiveintegers,returnsamatrix ofnumbersrandomly takenbetween0and1. rand()returnsarealnumberrandomlytakenbetween0and1. floor(x)returnstheintegerpartof realnumber.Inparticular,if isrealbetween 0and1,floor(rand()+p)willbe1with probabilityand0with1 probability.
  28. 33. Scilabforverybeginners-33/33 Displayandplot clf meansclearfigureandclearsthecurrentfigureonthegraphicswindow. plotallowstodrawcurvesandscatterplotsin2dimensions. linspace(a,b,n), withandreal andinteger, defines a vector ofvalues regularlyspacedbetween and . scfallowstoopenortoselectothergraphicswindowsthanthecurrentone. surfallows3-Dsurfaceplots. bar(X,Y)inwhichXandYarevectors,drawsthebargraphoftheseriesofvaluesfor XwhichhasfornumbersthevaluesofY. plot(X,Y,"*")drawsthescatterplotofcoordinates(X(i),Y(i))asstars.Thecolorcan bespecified. plot(Y,"+")drawsthescatterplotofcoordinates(i,Y(i))ascross. disp("Sentence")displayswhatiswrittenindoublequotes. disp(A)inwhichAisamatrixofnumbers,displaysthetableofthevaluesofA. disp("Sentence"+string(x))displaysthesentenceandthevalueofnumber . xclickreturnsthecoordinatesofthepointclickedinagraphicswindow. Utilities unique(v) returns the vector with a unique occurrence of its repeated components. sum(v)returnsthesumofalltheelementsofthevectororthematrix . prod(v)returnstheproductofalltheelementsofthevectororthematrix . find()returnstheindicesoftheelementsofvector satisfying thetest. disp(x,y,)displaysthevaluesofitsargumentsintheconsole. string(x)convertsnumber toastring. format(n)inwhich isanintegergreaterthanorequalto2,setsthedisplayto characters,includingthesignandthedecimaldot. zeros(n,p)definesa matrixthatonlycontainszeros. feval(x,y,f)inwhich and arerespectivelyvectorsofsize and ,definesthe matrix whoseelement( , )is ( , ). helpfunctionopensthehelpbrowserontherightfunctionpage. ticstartsaclock. tocstopstheclock.