33
 "#$%&' ()*+,-,$.+. "/0/" ! 123 '$. ,4+ 56+. 7+ 89: ; <=>>> ?+,.&$%%+. @A,&)#+B ; CCC/.#$%&';+)*+,-,$.+./#9D #$%&'( )*+ ,-+. (-/%00-+1

Scilab for very beginners (from official page)

Embed Size (px)

Citation preview

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 1/33

ScilabEnterprisesS.A.S-143bisrueYvesLeCoz-78000Versailles(France)-www.scilab-enterprises.com

Scilabforverybeginners

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 2/33

Scilabforverybeginners-2/33

Thisdocumenthasbeenco-writtenbyScilabEnterprisesandChristineGomez,mathematicsteacheratLycéeDescartes

(DescartesHighSchool)inAntony,Hauts-de-Seine(France).

©2013ScilabEnterprises.Allrightsreserved.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 3/33

Scilabforverybeginners-3/33

Tableofcontent

Introduction

Aboutthisdocument4

InstallScilab4

Mailinglist 4

Complementaryresources4

Chapter1–BecomefamiliarwithScilab

Thegeneralenvironmentandtheconsole5Simplenumericalcalculations 6

Themenubar7

Theeditor 8

Thegraphicswindow 9

Windowsmanagementandworkspacecustomization 11

Chapter2-Programming

Variables,assignmentanddisplay12

Loops16

Tests172and3Dplots18

Supplementsonmatricesandvectors23

Calculationaccuracy29

Solvingdifferentialequations30

Chapter3–UsefulScilabfunctions

Inanalysis32

Inprobabilityandstatistics32

Todisplayandplot33

Utilities33

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 4/33

Scilabforverybeginners-4/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.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 5/33

Scilabforverybeginners-5/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 =

161051.

Itispossibletocomebackatanymomentwiththekeyboard'sarrowkeys←↑→↓orwiththe

mouse.Theleftandrightkeysareusedtochangetheinstructionsandtheupanddownkeysare

usedtocomebackonapreviouslyexecutedcommand.

Mention

Beforetheresult,ansis

displayedfor“answer”.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 6/33

Scilabforverybeginners-6/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 =

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,thecalculationisdonebuttheresultisnotdisplayed.

-->(1+sqrt(5))/2; --> (1+sqrt(5))/2

ans =

1.618034

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 7/33

Scilabforverybeginners-7/33

Toremindthenameofafunction

ThenamesofcommonlyusedfunctionsaresummarizedinChapter3ofthisdocument(page32).

Forexample:

--> exp(10)/factorial(10)

ans =

0.0060699

Thetabkey→│onthekeyboardcanbeusedtocompletethenameofafunctionoravariableby

givingitsfirstfewletters.

Forexample,aftertypingintheconsolethecommand:

-->fact

andthenpressingthetabkey,awindowisdisplayedwithallthefunctionsandvariablesnames

beginning with fact, such as factorial andfactor. Just double click on the required

functionorselectitwiththemouseorwiththekeys↑↓andpressEnter(WindowsandLinux)

orReturn(MacOSX)toinsertitinthecommandline.

Themenubar

Themenuslistedbelowareparticularlyuseful.

Applications

• Thecommandhistoryallowsyoutofindallthecommandsfromprevioussessionstothecurrentsession.

•  Thevariablesbrowserallowsyoutofindallvariablespreviouslyusedduringthecurrent

session.

Edit

Preferences(inScilabmenuunderMacOSX)allowsyoutosetandcustomizecolors,fontsand

fontsizeintheconsoleandintheeditor,whichisveryusefulforscreenprojection.

Clickingon ClearConsole clears theentirecontent ofthe console.In thiscase,the command

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

clickonControl>Resume.

•  To quit for good a calculation without any possibility of return, typeabort in the

consoleorclickonControl>Abortinthemenubar.

Mention

Allavailablefunctionsare

alsolistedintheembedded

helpbyclickinginthemenu

baron?>ScilabHelp.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 8/33

Scilabforverybeginners-8/33

Theeditor

Typingdirectlyintotheconsolehastwodisadvantages:itisnotpossibletosavethecommands

anditisnoteasytoeditmultiplelinesofinstruction.Theeditoristheappropriatetooltorun

multipleinstructions.

Openingtheeditor

Toopentheeditorfromtheconsole,clickonthefirsticoninthetoolbar oronApplications

>SciNotesinthemenubar.

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).

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 9/33

Scilabforverybeginners-9/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

whichtheplotwillbedrawnbytypingscf(n);nforthe

graphicswindownumber

(mentionedonthetopleft).

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 10/33

Scilabforverybeginners-10/33

Modifyingaplot

Themagnifyingglass allowszooming.Tozoomintwodimensions,clickonthetoolandwith

the mouse create a rectangle which will constitute the new enlargedview. 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

Togethelpwithanyfunction,typehelpintheconsolefollowedbythenameoftheappropriate

function.Forexample:

-->help sin

displayshelpforsin(sine)function.

Mention

Examplesofusecanbe

executedinScilaband

editedinSciNotesinusing

theassociatedbuttonsin

theexampleframework.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 11/33

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.Whenthepositionistheoneyouwant,releasethemousebutton.Tocancelandbringoutthewindow,clickonthesmall

arrowontherightofthesamebar.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 12/33

Scilabforverybeginners-12/33

Chapter2-Programming

Intheexamplesgiveninthisdocument,anylineprecededby“-->“isacommand,theother

linesarethereturnsfromcommands(calculationresults,errormessages…).Donotwrite“-->“

in the editor. Theyare introduced hereto make the distinction between command lines and

calculationresults asit isdisplayedin theconsole aftercopying/pasting. Whenpresentedin a

table (without“-->“ and no calculation result), the commandsare depictedexactly as they

shouldbetypedintheeditor.

Variables,assignmentanddisplay

Variables

Scilabisnotacomputeralgebrasystem.Itcalculatesonlywithnumbers.Allcalculationsaredonewith 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.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 13/33

Scilabforverybeginners-13/33

Theresultofacalculationthatisnotassignedtoavariableisautomaticallyassignedtothe

variablecalledans:

-->3*(4-2)

ans =

6.

-->ans

ans =

6.

Functions

Functions arethe easiestand most naturalway to make computationsfrom variables andfor

obtainingresultsfromvariables.

A function definition begins withfunction and ends withendfunction.Forexample,to

converteuros(e)indollars(d)withanexchangerate(t),the dollarsfunctionisdefined.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.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 14/33

Scilabforverybeginners-14/33

Requestingtheassignmentofavariable

Assignmentismadeeasilyusingthe“=“operator.

Display

Writing

Typing thename of a variable displays itsvalue,exceptwhen 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 =

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] 

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 15/33

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:<<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.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 16/33

Scilabforverybeginners-16/33

orwhichdecreasesinstepsof4from20to2:

-->u=20:-4:2

u =

20. 16. 12. 8. 4.

For

Theeasiestloopstructureforafixednumberofiterationsiswrittenwith for … 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)

Whileh<7

  htakesthevalueh+0.3(thetreegrows)

  ytakesthevaluey+1(oneyearpasses)

Endwhile

Displayy(thefinalyear)

 

h=1.2;

y=2005;

 while h<7

h=h+0.3;

y=y+1;

end

disp("I will cut the..

tree in "+string(y))

Mention

Whenacommandistoolongtobewritteninoneline,theeditorwillwraplines.Onecanalsowraplinesusing“..“(twodots)beforegoingtothenextline.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 17/33

Scilabforverybeginners-17/33

Tests

Comparisonoperators

Useful tests include comparing numbers or determining whether a statement is true or false.

Belowthecorrespondingcommands:

Equal Different Less Greater LessorequalGreateror

equal

== <> < > <= >=

True False And Or No

%T %F & | ~

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 … then … else … end,

•  if … then … elseif … then … else … end.

if … thenmustbewrittenonthesamelineandlikewisewith elseif … then.

Mention

Becautiouswithcalculationaccuracy.Calculationsareapproachedand“==“willsometimesgivewrongresults(see

Calculationaccuracy,page30).

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 18/33

Scilabforverybeginners-18/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 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.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">".

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 19/33

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! →  !(!)thevaluesof xarespecifiedusingthelinspace commandbywriting:

x=linspace(a,b,n); inwhichaisthesmallestvalueofthevariable!,bthehighestvalue

of  !,andnthenumberofvaluescalculatedbetweenaandb.

Donotforgetthe“;“sympbolotherwiseallnvaluesof !willbedisplayed.

Forexample,considertwofunctions !and!definedovertheinterval[-2;5]by:

 ! ! = (!! + 2!)!!!,and! ! = sin!

!

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 20/33

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,thatof finredandthatofgin

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!(!)ofa vector!.plot(u,"*r") specifies the styleandcolorof the points in

quotes:redandnon-connectedstars.Bydefault,pointsareplottedinblueandareconnected.

ScilabEditor GraphicsWindow

for n=1:50

u(n)=(-0.8)^n;

end

clf; plot(u,"*r") 

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 21/33

Scilabforverybeginners-21/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.

ScilabEditor GraphicsWindow

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 !

•  Calculatez=feval(x,y,f)'

feval(x,y,f) returns the!×! matrix whose!"element is !(!!, !!)which will be

transposedbyusingthesinglequotesymbol“'“

•  Executesurf(x,y,z).

Toplotthesurface! = 2!!+ !

!(ellipticparaboloid):

ScilabEditor GraphicsWindow

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) 

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 22/33

Scilabforverybeginners-22/33

Curvesinspacemaybeplottedusingtheparam3dfunction.param3dhasthreearguments,x,

yandz,eachvectorshasthesamedimensionandcorrespondstothepoints (!! ,!! , !!)onthe

curve.

Toplotthehelixdefinedby(! = cos ! ,! = sin ! , ! = !):

ScilabEditor GraphicsWindow

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

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 23/33

Scilabforverybeginners-23/33

Statistics

Allthestandardstatisticalfunctionsarelistedonpage32.

Keepparticularlyinmind:

•  Thefunctionbar(x,n,color) whichdrawsbargraphs:

ScilabEditor GraphicsWindow

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:

ScilabEditor GraphicsWindow

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.

Parenthesesareusedtoaccesselementsortomodifythem.

Mention

Thiscommandcanalsobe

typedundertheform:

 m=[1,2,3;4,5,6]

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 24/33

Scilabforverybeginners-24/33

-->m(2,3)

ans =

6.

-->m(2,3)=23

 m =

1. 2. 3.

4. 5. 23.

The“:“operatorisusedtodesignatealltherowsorallcolumnsofamatrix.

Toviewthesecondrowofthematrix m ,type:

-->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]

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 25/33

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

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 26/33

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.Theparenthesesaround1arenecessarysothatthe

pointisnotconsideredasacommaaspartofthe

number1.Itisalsopossibletowrite1 ./Cwith

aspacebetween1and“.“

Solvinglinearsystems

Tosolvethelinearsystem AX=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.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 27/33

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.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 28/33

Scilabforverybeginners-28/33

Sumandproduct

Thesum andprodfunctionsrespectivelycalculatethesumandtheproductoftheirargument

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(w<5)

ans =

1. 3. 7. 8.

Theresultingvector(1,3,7,8)indicatesthatelements !!

,!!,!!and!!aresmallerthan5.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 29/33

Scilabforverybeginners-29/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

Numbershaveanabsolutevaluebetweenabout2.2×10-308

and1.8×10+308

.

Thenumber%epsequalsto2.220446049D-16givesthesmallestrelativeprecisionthatcanbeobtainedincomputations,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

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 30/33

Scilabforverybeginners-30/33

-->abs(a^2+b^2-c^2)<%eps

ans =

F

Theprogramrespondsfalsebecauseabsolute

precisioniscalledfor

-->abs(a^2+b^2-c^2)/c^2<%eps

ans =

T

Theprogramrespondstruebecauserelative

precisioniscalledfor

Display

Resultsaredisplayed,by default, with 10characters, including thedecimalpointand thesign.

Theformatfunctionisusedtodisplaymoredigits.Todisplay20digits,typeformat(20).

Reconsidering! = 3:

-->a^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

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 31/33

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 

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 32/33

Scilabforverybeginners-32/33

Chapter3–UsefulScilabfunctions

Analysis

•  sqrt(x) returns the square root of!with!real positive 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! ≤ ! < ! + 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 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 Y-

coordinatein blueandn2asY-coordinateingreen,with!,n1andn2beingsamesizelinevectors.

•  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.

7/27/2019 Scilab for very beginners (from official page)

http://slidepdf.com/reader/full/scilab-for-very-beginners-from-official-page 33/33

Displayandplot

•  clf means“clearfigure“andclearsthecurrentfigureonthegraphicswindow.

•  plotallowstodrawcurvesandscatterplotsin2dimensions.

•  linspace(a,b,n), with! and! real and! integer, defines a vector of! values

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!.

•  clickreturnsthecoordinatesofthepointclickedinagraphicswindow.

Utilities

•  unique(v) returns the vector ! with a unique occurrence of its repeated

components.

•  sum(v)returnsthesumofalltheelementsofthevectororthematrix !.

•  prod(v)returnstheproductofalltheelementsofthevectororthematrix!.

•  find(<test about v>)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.