Scilabforverybeginners
ScilabEnterprisesS.A.S-143bisrueYvesLeCoz-78000Versailles(France)-www.scilab-enterprises.com
Thisdocumenthasbeenco-writtenbyScilabEnterprisesandChristineGomez,mathematicsteacheratLycéeDescartes (DescartesHighSchool)inAntony,Hauts-de-Seine(France). ©2013ScilabEnterprises.Allrightsreserved.
Scilabforverybeginners- 2/33
Thisdocumenthasbeenco-writtenbyScilabEnterprisesandChristineGomez,mathematicsteacheratLycéeDescartes (DescartesHighSchool)inAntony,Hauts-de-Seine(France). ©2013ScilabEnterprises.Allrightsreserved.
Scilabforverybeginners- 2/33
Tableofcontent
Introduction Aboutthisdocument4 InstallScilab4 Mailinglist 4 Complementaryresources4
Chapter1–BecomefamiliarwithScilab Thegeneralenvironmentandtheconsole5 Simplenumericalcalculations 6 Themenubar7 Theeditor 8 Thegraphicswindow 9 Windowsmanagementandworkspacecustomization 11
Chapter2-Programming Variables,assignmentanddisplay12 Loops16 Tests17 2and3Dplots18 Supplementsonmatricesandvectors23 Calculationaccuracy29 Solvingdifferentialequations30
Chapter3–UsefulScilabfunctions Inanalysis32 Inprobabilityandstatistics32 Todisplayandplot33 Utilities33
Scilabforverybeginners- 3/33
Introduction
Aboutthisdocument Thepurposeofthisdocumentistoguideyoustepbystepinexploringthevariousbasicfeatures ofScilabfor a userwho hasneverused numerical computation software. Thispresentation is 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.
Scilabforverybeginners- 4/33
Chapter1–BecomefamiliarwithScilab 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
=
Mention Beforetheresult,ansis displayedfor“answer”.
161051.
Itispossibletocomebackatanymomentwiththekeyboard'sarrowkeys←↑→↓orwiththe mouse.Theleftandrightkeysareusedtochangetheinstructionsandtheupanddownkeysare usedtocomebackonapreviouslyexecutedcommand.
Scilabforverybeginners- 5/33
Simplenumericalcalculations Allcomputationsdone with Scilab arenumerical.Scilabperforms computationswith 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
while:
-->SQRT(9)
=
!--error 4
3.
Variable non définie: SQRT
Particularnumbers
%eand%pirepresentrespectively eandπ : --> %e %e
--> %pi
=
%pi
2.7182818
= 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
Scilabforverybeginners- 6/33
Toremindthenameofafunction
ThenamesofcommonlyusedfunctionsaresummarizedinChapter3ofthisdocument(page32). Forexample: --> exp(10)/factorial(10) ans
= 0.0060699
Mention Allavailablefunctionsare alsolistedintheembedded helpbyclickinginthemenu baron?>ScilabHelp.
Thetabkey→│onthekeyboardcanbeusedtocompletethenameofafunctionoravariableby givingitsfirstfewletters. Forexample,aftertypingintheconsolethecommand: -->fact
andthenpressingthetabkey,awindowisdisplayedwithallthefunctionsandvariablesnames beginning with fact, such as factorial and factor. Just double click on the required functionorselectitwiththemouseorwiththekeys↑↓andpressEnter(WindowsandLinux) orReturn(MacOSX)toinsertitinthecommandline.
Themenubar Themenuslistedbelowareparticularlyuseful. Applications •
•
Thecommandhistoryallowsyoutofindallthecommandsfromprevioussessionstothe currentsession. Thevariablesbrowserallowsyoutofindallvariablespreviouslyusedduringthecurrent session.
Edit Preferences (in ScilabmenuunderMacOSX)allowsyoutosetandcustomizecolors,fontsand fontsizeintheconsoleandintheeditor,whichisveryusefulforscreenprojection.
Clickingon Clear Console clears theentirecontent of theconsole. In this case, thecommand historyisstillavailableandcalculationsmadeduringthesessionremaininmemory.Commands thathavebeenerasedarestillavailablethroughthekeyboard’sarrowkeys. Control
Tointerruptarunningprogram,youcan: •
•
•
TypepauseintheprogramorclickonControl>Interrupt inthemenubar(CtrlXunder WindowsandLinuxorCommandXunderMacOSX),iftheprogramisalreadyrunning. In all cases, the prompt “-->“ will turn into “-1->“, then into “-2->“…,if the operationisrepeated. Toreturntothetimepriortotheprograminterruption,typeresumeintheconsoleor clickon Control>Resume . To quit for good a calculation without any possibility of return, type abort in the consoleorclickon Control>Abort inthemenubar.
Scilabforverybeginners- 7/33
Theeditor Typingdirectlyintotheconsolehastwodisadvantages:itisnotpossibletosavethecommands anditisnoteasytoeditmultiplelinesofinstruction.Theeditoristheappropriatetooltorun multipleinstructions. Openingtheeditor
Toopentheeditorfromtheconsole,clickonthefirsticoninthetoolbar >SciNotesinthemenubar.
oronApplications
Theeditoropenswithadefaultfilenamed“Untitled 1“.
Writingintheeditor
Typingintheeditorislikeasinanywordprocessor. Inthetexteditor,openingandclosingparentheses,endloops,functionandtestcommandsare addedautomatically.However,thesefeaturescanbedisabledinOptions>Auto-completionon menu,inclickingonthetwobelowentriesenabledbydefault: (,[,… if,function,…
• •
While inprinciple each instructionshouldbe entered on a separateline,it ispossible to type multiplestatementsonasamelineseparatingeachstatementwithasemicolon“ ;“. Aspaceatthestartofthelinecalledindentationisautomaticwhenalooporatestisstarted. Inthefollowingexample,wecalculate10termsofthesequence (! )definedby: !
!!
=
!!!!
1 =
2 !!
−3
Mention -Commentsprecededwith“//“willnotbetakenintoaccountinthecalculations. -Tochangethefont,clickonOptions>Preferences. -Whenwritingaprogram,indentationisautomatic.Ifthisisnotthecase,clickonEdit>Correctindentationtorestoreit(CtrlI underWindowsandLinuxorCommandIunderMacOSX).
Scilabforverybeginners- 8/33
Saving
Anyfilecanbesavedbyclickingon File>Saveas . Theextension“.sce“attheendofafilenamewilllaunchautomaticallyScilabwhenopeningit (exceptunderLinuxandMacOSX). Copyingintotheconsole,executingaprogram InclickingonExecuteinthemenubar,threeoptionsareavailable: •
•
•
Execute“…filewithnoecho“(CtrlShiftEunderWindowsandLinux,CmdShiftEunder MacOSX):thefileisexecutedwithoutwritingthe programintheconsole(savingthe filefirstismandatory). Execute “…filewithecho“(CtrlLunderWindowsandLinux,CmdLunderMacOSX): rewritethefileintotheconsoleandexecutesit. Execute“…untilthecaret,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).
Scilabforverybeginners- 9/33
Modifyingaplot
Themagnifyingglass allowszooming.Tozoomintwodimensions,clickonthetoolandwith the mouse create a rectangle which will constitute the newenlarged view. To zoomin 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
Mention Examplesofusecanbe executedinScilaband editedinSciNotesinusing theassociatedbuttonsin theexampleframework.
Togethelpwithanyfunction,typehelpintheconsolefollowedbythenameoftheappropriate function.Forexample: -->help sin
displayshelpforsin(sine)function.
Scilabforverybeginners- 10/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.
Scilabforverybeginners- 11/33
Chapter2-Programming
Intheexamplesgiveninthisdocument,anylineprecededby“-->“isacommand,theother linesarethereturnsfromcommands(calculationresults,errormessages…).Donotwrite“-->“ in the editor. Theyare introduced hereto makethe distinction between command lines and calculationresults asit isdisplayedin theconsole after copying/pasting.Whenpresented ina table (without“ -->“ and no calculation result), the commands aredepicted exactlyas 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,matricesofdimension1×n orn×1andanumberisitselfamatrixofdimension1×1. 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
Ifavalueisassignedtothevariable a,thereisnolongeranerror: --> a=%pi/4 a
= 0.7853982
--> a a
= 0.7853982
Variablesmaytakeanynamethatisnotalreadydefinedbythesystem: --> Piby2=%pi/2 Piby2
=
1.5707963
Mention LiketheScilabfunctions,a variablenamemustnot haveaccentsorspecial characters.
Scilabforverybeginners- 12/33
Theresultofacalculationthatisnotassignedtoavariableisautomaticallyassignedtothe variablecalled ans: -->3*(4-2) ans
= 6.
-->ans ans
= 6.
Functions
Functions arethe easiestand most naturalway to make computationsfrom variables andfor obtainingresultsfromvariables. A functiondefinition begins with functionandendswith endfunction.Forexample,to converteuros(e)indollars(d)withanexchangerate(t),the dollarsfunctionisdefined.The variablesare eandtandtheimageis d. -->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
Mention Thevariablesxandyare dummyvariables,their namescanbereusedwhen definingotherfunctionsor inScilab.
Thedefinedfunctionscanthenbeusedtocalculatevalues: --> f(10) ans
= 4.4999745
--> g(12.5) ans
= 9.5555556
Scilabforverybeginners- 13/33
Requestingtheassignmentofavariable
Assignmentismadeeasilyusingthe“=“operator.
Display
Writing Typing thename of a variable displays itsvalue, except when there is “;“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
Mention Thiscommandcanalsobe typedundertheform:
= 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:
m=[1,2,3;4,5,6;7,8,9]
Scilabforverybeginners- 14/33
dispfunction
dispmustalwaysbeusedwithparentheses. Withthevector vpreviouslydefined: -->v(2) ans
=
- 2.
-->disp(v(2)) - 2.
Todisplayastring(usuallyasentence),putitbetweenquotes: -->disp("Bob won") Bob won
Todisplayacombinationofwordsandvaluesusethe stringcommandwhichconvertsvalues 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:<<beginningvalue:step:endingvalue>>.Itispossiblethat“endingvalue”is 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. Scilabforverybeginners- 15/33
orwhichdecreasesinstepsof4from20to2: -->u=20:-4:2 u
= 20.
16.
12.
8.
4.
For
Theeasiestloopstructureforafixednumberofiterationsiswrittenwith for … end.
Example:Calculationof20termsofasequencedefinedbyrecurrenceby:
Algorithm
Scilab Editor
Put4inu(1)
u(1)=4;
Fornfrom1to20
for n=1:20
u(n+1)takesthevalueu(n)+2n+3
u(n+1)= u(n)+2*n+3;
andu(n)
disp([n,u(n)])
Displaynandu(n)
!!
=
!!!!
4 =
!!
+ 2! + 3
end
Endfor
While
Tostopaloopwhenagivengoalisreached, while … endisused.
IplantedaChristmastreein2005measuring1.20m.Itgrowsby30cmperyear.Idecidedtocut itwhenitexceeds7m.InwhatyearwillIcutthetree? Algorithm
Scilab Editor
Put1.2inh(h=treeheight)
h=1.2;
Put2005iny(y=year)
y=2005;
Whileh<7
while h<7
htakesthevalueh+0.3(thetreegrows)
h=h+0.3;
ytakesthevaluey+1(oneyearpasses)
y=y+1;
Endwhile
end
Displayy(thefinalyear)
disp("I will cut the.. tree in "+string(y))
Mention Whenacommandistoolongtobewritteninoneline,theeditorwillwraplines.Onecanalsowraplinesusing“..“(two dots)beforegoingtothenextline.
Scilabforverybeginners- 16/33
Tests Comparisonoperators
Useful tests include comparing numbers or determining whether a statement is true or false. Belowthecorrespondingcommands: Equal
Different
Less
Greater
Less or equal
Greateror equal
==
<>
<
>
<=
=>
True
False
And
Or
No
%T
%F
&
|
~
Mention Becautiouswithcalculationaccuracy.Calculationsareapproachedand“==“willsometimesgivewrongresults(see Calculationaccuracy,page30).
Tocomparetwovectors(ortwomatrices),thetests“ ==“and“<>“willcomparetermbyterm. Forexample: -->X=[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
If…then
Thebasicconditionalstatementsarethefollowing: • •
if
…
if if
… …
then then
… …
else … end, elseif … then
…
else
…
end.
thenmustbewrittenonthesamelineandlikewisewith elseif
…
then.
Scilabforverybeginners- 17/33
Example:Alicethrowsthreedice. • • • •
Ifshegetsthree6’sshewins$20, Ifshegetsthreeidenticalnumbersdifferentfrom6shewins$10, Ifshegetstwoidenticalnumbersshewins$5, Otherwiseshewinsnothing.
SimulateatrialandcalculateAlice’swinningsusingthefunctions: grand(seepage22), unique(D)whichkeepsonlyoncethevaluesthatappearsseveraltimesinD, length(unique(D))whichreturnsthesizeoftheobtainedvector,thatistosay1if threediceareequal,and2iftwodiceareequal. •
• •
Algorithm
Scilab Editor
PutthethreevaluesinD
D=grand(1,3,"uin",1,6);
IfAlicegetsthree6,then
if D==[6,6,6] then
Alicewins20dollars Elseifshereceivesthreeidenticalvalues, then Alicewins10dollars
W=20; elseif length(unique(D))==1 then W=10; elseif length (unique(D))==2 then
Else,ifshereceivestwoidenticalvalues,then Alicewins5dollars
W=5; else
Otherwise Alicewinsnothing Endif
W=0; end disp("Alice wins "+..
DisplayAlice'swinnings
string(W)+ " dollars")
2-Dand3-Dplots
plotcommandisusedtocreateplotsintheplane.Colorand appearancecanbe specifiedby 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","<",and ">".
Scilabforverybeginners- 18/33
Basicplots
Toplotapoint PlotthepointA(1;2)witharedpoint. Scilab Editor
Graphics Window
plot(1,2,".r")
Toplotasegment Plotthesegment[AB]inblue(bydefault)withA(1;2)andB(3;5). Scilab Editor
Graphics Window
plot([1,3],[2,5])
Plotsofplanecurvesdefinedbyfunctionsy=f(x)
! (! )thevaluesof xarespecifiedusingthelinspace commandbywriting: x=linspace(a,b,n); inwhich aisthesmallestvalueofthevariable !, bthehighestvalue of ! ,and nthenumberofvaluescalculatedbetweenaandb. Forafunction!
→
Donotforgetthe“;“sympbolotherwiseallnvaluesof ! willbedisplayed.
Forexample,considertwofunctions !and! definedovertheinterval[-2;5]by: !
!
=
(! ! + 2! )! ! ,and ! !
!
=
sin
!
!
Scilabforverybeginners- 19/33
Withtheprogrambelow,weplotthecurvedefinedby !,inbluebydefault: Scilab Editor
Graphics Window
function y=f(x) y=(x^2+2*x)*exp(-x) endfunction x=linspace(-2,5,50); plot(x,f)
Byaddingtheprogrambelow,weobtaintheplotoftwocurves,thatof finredandthatofgin green.Thepreviousplotwasclearedthroughtheclfcommand(“clearfigure“). Scilab Editor Graphics Window
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!(!)ofa vector!. plot(u,"*r") specifies the styleandcolorof the points in quotes:redandnon-connectedstars.Bydefault,pointsareplottedinblueandareconnected. ,
Scilab Editor
Graphics Window
for n=1:50 u(n)=(-0.8)^n; end clf; plot(u,"*r")
Scilabforverybeginners- 20/33
Bivariatestatisticaldata Bivariate statistical data are given in the form of two vectors: let’s call them X and Y. plot(X,Y,"<")willplotascatterplotof !( !! ; !! )withbluetriangles. Scilab Editor
Graphics Window
X=[1,3,3,7,7,9,10]; Y=[8,7,5,5,4,2,2]; clf; plot(X,Y,"<")
Plotsin3dimensions
Scilabcanbeusedtoplotsurfacesandcurvesinspace,withmanyoptionsforthetreatmentof hiddenfaces,facecolors,pointsofview,etc.Thefollowingexampleswillillustrate3-Dplots. Thesurffunctioncanbeusedforplottingsurfaces.Thisfunctionhasthreeinputvariables,x,y andz.xandyarerespectivelyvectorsofsize!and!correspondingtopointsontheaxes(!" ) and(!"). zisamatrixofdimension!×!withelement!!" correspondingtotheheightofthe pointwithX-coordinate!! andY-coordinate!! . Toplotthesurfacedefinedbyafunctionoftheform • •
•
!
=
! (!
,
! ),itisnecessaryto:
Definefunction ! Calculate z=feval(x,y,f)' feval(x,y,f) returns the !×! matrix whose!"element is ! (!!
,
!! )which
will be
transposedbyusingthesinglequotesymbol“'“ Execute surf(x,y,z).
Toplotthesurface!
=
2!
!
Scilab Editor
+!
!
(ellipticparaboloid): Graphics Window
function z=f(x,y) z=2*x^2+y^2; endfunction x=linspace(-1,1,100); y=linspace(-2,2,200); z=feval(x,y,f)'; clf surf(x,y,z)
Scilabforverybeginners- 21/33
Curvesinspacemaybeplottedusingtheparam3dfunction.param3dhasthreearguments,x, yand z,eachvectorshasthesamedimensionandcorrespondstothepoints (!! !! !! )onthe curve. ,
Toplotthehelixdefinedby(!
=
cos
!
,
!
=
Scilab Editor
sin !
,
!
=
,
! ):
Graphics Window
t=linspace(0,4*%pi,100); param3d(cos(t),sin(t),t)
Simulationsandstatistics
SeveralfunctionsareavailableinScilabtoperformsimulationsquicklyandefficiently. Randomsequences •
grand(1,p,"uin",m,n) returnsavectorof!randomintegersequencesbetween !
and!with !positiveinteger,!and!integersand!
≤
!
.
-->t= grand(1,4,"uin",1,6) t
= 3.
•
1.
3.
6.
grand(1,p,"unf",a,b) returns a vector of!random real sequences between! and! with !positiveinteger,!and! realand !
≤ ! .
-->tr= grand(1,2,"unf",-1,1) tr
=
- 0.7460264
0.9377355
Scilabforverybeginners- 22/33
Statistics
Allthestandardstatisticalfunctionsarelistedonpage32. Keepparticularlyinmind: •
Thefunctionbar(x,n,color) whichdrawsbargraphs:
Scilab Editor
Graphics Window
x=[1:10]; n=[8,6,13,10,6,4,16,7,8,5]; clf; bar(x,n)
•
Forabargraphrepresentingtwosetssidebyside:considertheseriesofvaluesXand thetwoseriesofnumbersn1andn2.Forplotting,n1and n2mustbecolumnvectors thatiswhytransposesareusedintheexamplebelow:
Scilab Editor
Graphics Window
X=[1,2,5];n1=[5,10,5];n2=[6,8,7]; bar(X,[n1',n2'])
Thecoloroptionalargumentdefinesthecolorasintheplotfunction.
Additionalinformationonmatricesandvectors Accessingelements
Square braces are used to define matrices. A space or a comma isused to switch from one columntoanotherandsemicolonsareusedtoswitchfromonelinetoanother.
-->m=[1 2 3;4 5 6] m
= 1.
2.
3.
4.
5.
6.
Mention Thiscommandcanalsobe typedundertheform:
m=[1,2,3;4,5,6]
Parenthesesareusedtoaccesselementsortomodifythem. Scilabforverybeginners- 23/33
-->m(2,3) ans
= 6.
-->m(2,3)=23 m
= 1.
2.
3.
4.
5.
23.
The“:“operatorisusedtodesignatealltherowsorallcolumnsofamatrix.
Toviewthesecondrowofthematrix ,type: m -->m(2,:) ans
= 4.
5.
23.
Andthethirdcolumn: -->m(:,3) ans
= 3. 23.
Toobtainthetransposeofamatrixoravectorusethesinglequotesymbol“'“: -->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]
Scilabforverybeginners- 24/33
B
= 1. 1. 2.
-->A*B ans
= Matrixmultiplication
9. 21. -->A*A !--error 10
Dimensionsarenotconsistent
Inconsistent multiplication. -->A.*A ans
= Elementwisemultiplication
1.
4.
9.
16.
25.
36.
-->2*(A+2) ans
= 6.
8.
10.
12.
14.
16.
Theoperationisperformedoneachelement because2isanumber
GivesthematrixXforwhichX*A=A Theexactresultis: 1.0 01.
-->A/A ans
= 1.
1.518D-16
3.795D-15
1.
Forreasonsofcalculationaccuracy,theresultcan beslightlydifferentdependingonyourversionof Scilabandyouroperatingsystem(seecalculation accuracy,page29).
-->A./A ans
= Givesthematrixdividedelementwise
1.
1.
1.
1.
1.
1.
Inthecaseofvectors: -->C=1:4 C
= 1.
2.
3.
4.
-->C*C !--error 10
Dimensionsarenotconsistent
Inconsistent multiplication.
Scilabforverybeginners- 25/33
-->C.*C ans
= 1.
4.
9.
16.
ItisalsopossibletowriteC^2 because,for vectors,exponentsareinterpretedasanoperation elementwise.Thisisnotthecasewithmatrices.
-->1/C ans
= 0.0333333
Inthisparticularcasewithvectors,wefindthe vectorXforwhichC*X=1
0.0666667 0.1 0.1333333 -->(1)./C ans
= 1.
0.5
0.3333333
0.25
Reverseelementwise Aspreviously,C^(-1) ispossible.The parenthesesaround1arenecessarysothatthe pointisnotconsideredasacommaaspartofthe number1.Itisalsopossibletowrite1 ./C with aspacebetween1 and“.“
Solvinglinearsystems
TosolvethelinearsystemAX=Y,inwhichAisasquarematrix,usethebackslash“\“ X=A\Y. 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=A\Y X
= - 0.5 0. 0.5
-->A*X ans
= 1. 1.
Scilabforverybeginners- 26/33
Someusefulfunctions
Sort Thegsortfunctionisusedtosorttheelementsofavectorinascendingordescendingorder. -->v=[2,6,9,6,-4,0,2] v
= 2.
6.
9.
6.
- 4.
0.
2.
2.
2.
6.
6.
9.
6.
2.
2.
0.
- 4.
--> gsort(v,"g","i") ans
=
- 4.
0.
--> gsort(v) ans
= 9.
6.
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.
Scilabforverybeginners- 27/33
Sumandproduct The sum and prodfunctionsrespectivelycalculatethesumandtheproductoftheirargument 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.
2.
6.
9.
0.
2.
-->unique(v) ans
=
- 4.
0.
Find Thefindfunctionsearchesforelementsinavectororamatrixandreturnsavectorcontaining thecorrespondingindices. Tofindalltheelementsofthevector!smallerthan5: -->w=[1,5,3,8,14,7,3,2,12,6]; find(w<5) ans
= 1.
3.
7.
8.
Theresultingvector(1,3,7,8)indicatesthatelements
!! , !! , !!
and!! aresmallerthan5.
Scilabforverybeginners- 28/33
Tofindalltheelementsofthevector!equalto3: -->w=[1,5,3,8,14,7,3,2,12,6]; find(w==3) ans
= 3.
7.
Theresultingvector(3,7)indicatesthatelements
!!
and!! areequalto3.
Accuracycomputation Computation -308
Numbershaveanabsolutevaluebetweenabout2.2×10
and1.8×10
+308
.
Thenumber %epsequalsto 2.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
=
Theprogramrespondsfalse becausethevalueofa^2+b^2isapproximate
F
Scilabforverybeginners- 29/33
-->abs(a^2+b^2-c^2)<%eps ans
Theprogramrespondsfalsebecauseabsolute precisioniscalledfor
=
F -->abs(a^2+b^2-c^2)/c^2<%eps ans
Theprogramrespondstruebecauserelative precisioniscalledfor
=
T
Display
Resultsaredisplayed,by default, with 10characters, including thedecimalpointand thesign. Theformatfunctionisusedtodisplaymoredigits.Todisplay20digits,type format(20) . Reconsidering!
=
3:
-->a^2 ans
Herethereare7decimalplaces,andwedonotsee theerror.
= 3.
-->format(20) Herethereare17decimalplaces,andwecansee theerror
-->a^2 ans
= 2.99999999999999956
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
Scilabforverybeginners- 30/33
Thesolutionyisamatrixofdimension n × T :
!! 1
!! 2
⋮
!! !
!! 1
!! 2
⋮
!! !
⋮
⋮
!! 1
Example:Solvingthedifferentialequation
!
"
!! 2
…
!! !
−!!
=
! !
⋮
=
! ! ,
!
!
=
!
Thisequationoforder2isreducedtoasystemoftwoequationsoforder1asdefinedby: !
=
! ( 1) ! ( 2)
! =
!′
,
!"#
%$=
!"#$% (1) !"#$% (2)
=
!′ !
"
Comment
!"#$% and !"#
%$1 2
2
=
=
−4×! (1)
Scilab Editor function yprim=f(t,y)
Wedefinethefunctionreturningoutputvectory’ frominputvariablestandy(yisavector). Wedefinethevaluesoftforplotting.
yprim(1)=y(2); yprim(2)=-4*y(1) ; endfunction
(thesolverchoosesitselfthegoodvaluesoftfor t0=0; tmax=5; theinternalcomputationofthesolution). Wedefinetheinitialconditions.
t=t0:0.05:tmax;
Weexecuteode.
y0=3; yprim0=0;
Weplottheintegralcurveofywithrespecttot.
y=ode([y0;yprim0],t0,t,f); clf; plot(t,y(1,:))
Scilabforverybeginners- 31/33
Chapter3–UsefulScilabfunctions
Analysis •
• • • • • •
sqrt(x) returns the square root of!with !realpositive or zero,and the complex rootofrealpositivepartotherwise. log(x)returnsthenaturallogarithmof xwith xrealorcomplexnumber. exp(x)returnstheexponentialof!with !realorcomplexnumber. abs(x)returnstheabsolutevalueof!real(orthemoduleif !iscomplex). int(x)returnsthetruncationof!real(theintegerbeforethedecimal). floor(x)returnstheintegerpartof!real(theinteger!forwhich ! ≤ ! < ceil(x)for!realreturnstheinteger!forwhich ! − 1 < ! ≤ !.
!
+ 1).
Probabilityandstatistics •
factorial(n) returnsthefactorialof nwith n 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 integer 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,3…asX-coordinates. bar(v,[n1’ ,n2’ ]) draws a double bar graph with ! as X-coordinate, n1 as Ycoordinatein blueandn2asY-coordinatein green,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 !probabilityand0with 1 − !probability.
Scilabforverybeginners- 32/33