Home

Scilab for Real Dummies

image

Contents

1. 19 Examples Set 6 Additional examples mostly related to Chapters 15 19 Q Return to Contents Example 6 1 user defined GUI introduction This example is a modification of the similar in Antonelli Chiaverini Introduzione a Scilab 5 3 pp 74 10 m The task is to create a GUI in the Graphics Window GW The GUI consists of A sine plot A slider for changing the angular frequency of the plot Two radiobuttons by which the properties of the plotted graph can be changed An exit button that closes the GUI The process is shown as a flow diagram to the right Create initial GUI Any changes EXIT pressed Close GUI END Implement changes No Ex 6 1 user defined GUI script 1 592 Go to the MAIN program below if you want to proceed in a logical order The first subroutine initial_GUI creates the initial sine plot within the Graphics Window including title and axes labels The initial angular frequency w is defined as 5 Hz There is really nothing special here Generates on the Graphics Window GW a GUI that contains a sine plot plot2d a slider by which to adjust the angular 7 trequency of the sine function two radiobuttons that change the style and color of the sine graph and a pushbutton that Closes the GW 7 clear clc SUBROUTINES
2. The Help Browser 2 3 2 The Graphics Graphic window number 0 Window with the plot ae pops up in this cases it B G i ale briefly flashes the first focemm e plot 1 In the script box with examples Click on the Execute icon to see how the scripts executes not all work 3 Click on the Editor icon and the script is transferred to Scilab s text Editor where you can play with it must be saved before it can be run The Help Browser 3 3 help function __ name BB Scilab Console To find the proper use peteeres Appicstions 2 of any function a assuming that the name is known the Help Browser can be opened from the Console by entering the command help function_name cond Linear Algebra eigenmarkov Scilab manual gt gt Linear Algebra gt det command in the p oee det shown case help p Serie det the brackets io Calling Sequence can be omitted The oto ae alternative is to open con Arguments the Browser with the Be i real or complex square matrix polynomial or rational matrix Help icon The Editor SciNotes A Save amp execute The Text Editor is where executable Scilab scripts are written maintained amp run m Open the Editor by clicking on the Launch SciNotes icon in the Console or by clicking Applications SciNotes suntited 1 OQ A Scilab script is a text file with a name of the type x sce the alterna
3. E items from A sin 2 x Element by element multiplication y A si x by u the wan E and frees nica I Plot command memory e clc cleans the Console the echo signal is mainly erased Thus our final script looks like this Pay e cli wipes an open Graphics attention to the semicolon at the end Window of each expression apart from the last Careful with clear it may cause havoc in some cases there will be a demo on this later Example 1 2 the task a decaying linear chirp a Write the script for a linearly frequency modulated sinusoidal Signal s t i e a linear chirp of the type s t A t sin 2m kot p where k is the rate of frequency change or chirp rate Use 2 5 periods of the basic frequency The amplitude should decay exponentially A t 2e 2 The initial phase shift shall be 1 4 Plot and print the result with a plotting method that differs from the previous one a The plot shall have grid title and axis labels Plug in the commands plot histplot surf 0 and plot3d on the Console to view examples of Scilab plots See also Chapter 7 Ex 1 2 first iteration m The linspace Q function creates M Fmodulationil ace a linearly space plotting vector Plots a sinusoidal function of the type with the arguments from to i 7 PREN he w ra l gt velocity x t frequency modulation phi number of points The default phase shift and A t amp
4. Min max position amp value A variation of the minQ and max functions allow us to determine the position and value of the smallest alt largest matrix element min_value min_pos min A picks out the position and value in this order of the smallest element in the matrix max_val max_pos max A the largest Note 1 The designation of vector elements here min_val etc is irrelevant Note 2 If the matrix contains multiple min max values only the position of the first is returned gt A 53 1 2 46 gt min_val min_pos min A min_pos ae min_val 1 gt max_val max_pos max A max_pos ames max_val 6 mean gt A 1 23 45 6 And the previously mentioned logic a a final time with the mean i 2 3 function 4 5 16 mean A returns the mean i n n value of all matrix elements mean A r returns a row vector consisting of the mean of each column mean A c returns a column vector containing the mean of m each row size gt V1 12 3 4 gt V2 Vv1 gt A 1234 567 8 The function size can be ee i gt size A used to find out the size of a ie matrix l 4 2 4 The answer is given as the mon number of rows and columns in that order ne gt N m size 1 2 3 4 5 6 m When row and column me variables are named the 3 answer is given in alphabetic ve or
5. Time s odeoptions gaz h Defining ODEOPTIONS variable XXREKARNEKARA KARE RARE RAKE KAREX Meaning of itask and tcrit 1 normal computation at specified times 2 computation at mesh points given in first row of output of ode 3 one step at one internal mesh point and return 4 normal computation without overshooting tcrit 5 one step without passing tcrit and return The command ts aa aa o imal Coon aa N a idiot re j 5 ais ODEOPTIONS odeoptions papi apars a a 5 internally generated banded jacobian see ml mu opens the GUI shown right With Iae 40 minds ie be kaa dapo oe of the banded jacobian the band is the i j s with i ml j ny 1 the help of it you can change han dhepa ADO parameters for solving differential aly ly ay Lm possbiy non zero ets equations Examples task 1234 5 U0 e hO size of first step ee e hmax maximum step size fax fcc ie Man e hmin minimum step size hmin min step size 0 e mxstep minimum of steps jctype 0 1 23 45 2 2 mxstep max number of steps allowed 500 500 Check with Help for details maxordn nasnumran tf re alowed at ost 2 12 12 maxords maximum stiff order allowed atmost 5 5 5 ixpr print level O or 1 0 m m 4 0 Johnny Heikell 14 Examples Set 5 The examples give additio
6. Ex 4 3 vase plot Not bad eh But I have no idea where the pink amp aniline colors came from they bumped up when I executed the script after The gray scale returned after I reloaded Scilab for a second time Example 4 4 ballot engine for politicians m The function on the next two slides is a ballot machine that help politicians Fe ales decide on how to cast their vote The number of issues to vote on is entered and the code checks that the number is a positive integer m Scilab then draws random numbers and transforms them to verbal votes yes no abstain The votes are finally put into groups of three m The function demonstrates the use of select case end with a finishing modulo statement o m It also shows the use of repeated if os end statements necessary or not Ex 4 4 script 1 2 voting sci A good part of the ue 3 Ballot machine for politicians The number function commands of issues to be voted on is entered and are related to _ Scilab tells how to vote on them The checking the validity answers are presented in groups of three of data clear clc The first check makes funcprot 0 sure that the number functi ti entered by the user is unction voting gt 0 Give input and check entered number The next check is to n input Give number of issues to vote on_ make sure that n is an ifn lt Odo of votings must be g
7. M to S translator script 2 4 Everything runs smoothly here The code is expected to present the sum and difference patterns for a monopulse antenna tracking radar etc Norm aperture with N elements N fs na xna na 1 2 1 N 1 1 2 Illumination Function wxna 1 1 N 2 ones 1 N 2 wxna mtlb_i wxna N 2 1 N ones 1 N 2 wxnb 1 1 N 2 ones 1 N 2 wxnb mtlb_i wxnb N 2 1 N ones 1 N 2 Fill with M 2 zeros front and back M 1024 xna na 1 2 1 N M 1 1 2 wxna zeros 1 M 2 wxna zeros 1 M 2 wxnb zeros 1 M 2 wxnb zeros 1 M 2 Beam Functions from fs 2 to fs 2 in sine space Nfft max size wxna Esine mtlb_fft wxna Nfft Esine fftshift Esine M to S translator script 3 4 Here comes more warnings May relate to a rounding error Esum mtlb_fft wxnb Esum fftshift Esum Azimuth vector sinfi fs 4 Nfft 2 Nfft 2 1 Nfft Azimuth vector in radians 1 L 45 If sinfi is outside 1 1 complex part of output of asin sinfi will be the opposite of Matlab one fi asin sinfi Beam gain functions Gfi Esine conj Esine Nfft Gfs Esum conj Esum Nfft Gfi mtlb_i Gfi 1 Nfft 2 sqrt Gfi 1 Nfft 2 Gfi mtlb_i Gfi Nfft 2 1 Nfft sqrt Gfi Nfft 2 1 Nfft Gfs sqrt Gfs M to S translator script 4 4 ld Note that titleQ is an alternative to xtitleQ Here come the last w
8. Trial and error showed that abort had the expected effect of jumping to the end of the function Good old GO TO statement where have you been all these years and why do they give you such fancy names Example 4 5 nested structures script while end structure This script contains an if fy Sone eNaleee elseif else end Climb up or down the scale depending on structure nested within an input data u or d without exceeding the limits The process ends when e is E pressed read the title for an explanation of what the 123456078 9 daily Sey climb jle reset counter script does strg strg empty string while strg e Until the e key is hit disp scale i Display location on scale Note how strg input Exit e Up u Down d string min and U if strg u then If u is hit TORR MAMET C Seo one stp up ant highest SON i if strg uti is hi that scale limits 5 i max i 1 1 One step down until lowest are not xo elseif strg e then If e is hit f break Jump out of the loop exceeded else Whatever else is hit disp incorrect input Present error message end End of if statement end End of while statement disp you hit e Exit Exit message Example 4 5 execution The scale counter i is preset to 1 and increases decreases depending on the entered
9. Same as before contour x y Z 10 flag 0 0 0 First flag argument plot3d x y Z theta 60 alpha 80 Turn 60 and 80 deg Mixed 2D 3D plots 2 2 plot The surface looks different from when it was plotted using surfQ The reason is that the x and y axes are inverted compared with the earlier case No point in denying there remains unsolved issues regarding the behavior of Scilab in this case 3D plot with hole The nan function allows certain z values to be excluded from a 3D 0 eo There is Polish logic behind the z arguments that asks for trial amp error to get it right subplot Subplots are a way of presenting multiple graphs on a single frame m The function subplot m n p or mnp splits the Graphics Window into m rows and n columns and the subplot in case occupies position p In the case of four subwindows subplot 22p the position of p is as shown m We ll do it for the z 2 x y exp x 0 5 y by fusing the four earlier cases into a single frame subplot demo script subplot sce Presents different aspects of the function z 2x42 yA2 exp x 2 0 5y 2 in four subplots clear clc clf x linspace 2 2 30 y linspace 3 3 30 X Y meshgrid x y Z 2 X 2 Y 2 exp X 2 0 5 Y 2 subplot 221 surf X Y Z subplot 222 contour x y Z 10 x linspace 2 2 10 y linspace 3 3 10 X Y meshgrid x y
10. The Colon Operator emerged in the earlier examples It is one of the most important operators in Scilab m A typically use is in the form 0 pi 36 pi Meaning Starting at 0 step by T 36 up to mT The first example shows that the truncated form 1 8 produces a row vector with increment 1 The second shows how to refer to rows 3 4 column 2 of the magic square Operators 2 4 qmo examples with The second example on the previous slide was a case of subscript manipulation of the type M j k where i j refers to the i th to j th rows and k to the k th column There is often need to address part of a matrix The idea should be understood well Below are three more examples Note that the Colon Operator alone refers to the entire row or column gt M testmatrix magi 4 gt M testmatrix magi 4 gt M testmatrix magi 4 gt A M 2 3 2 3 gt B M 3 gt C M 3 4 3 10 6 15 Operators 3 4 the Operator The Operator refers to the last value 1 to the value next to the last etc The example to the right shows some uses of the Operator The Operator can be used to flip the order of elements in a vector as shown below an alternative method was demonstrated in Ex 1 3 Task 1 gt M testmatrix magi 4 gt v 3456789 gt v 1 1 ans Operators 4 4 the Backslash Operato
11. Cyan m Magenta y Yellow the letter should be in front of the style code inside single or double quotes e g r 3D graphs plot3sd m The syntax of plot3dQ is quite similar to that of plot2dQ In addition to the mandatory x y z arguments the plot 3dQ function can among other possibilities have following arguments plot3d x y z theta alpha leg flag ebox m Check with Help for an explanation Below we ll plot a 3D graph of the sinc function sin x x using some of the surface definition capabilities of plot3dQ Scilab defines only the 2D sinc x function so to shift to 3D we will apply the expression ray a Of the above mentioned arguments we ll use leg X Y 7Z to label x y and z axes and flag mode type box to define surface color scaling and frame of the plot 3D graphs plot3d script amp plot for 3D sinc Pay attention to X Y ndgrid x y amp use of the Dot Operator in Z AN ANN LNW 7 es ii TAN iii ve fee i h AN ee 6 BRR SSS ST CK SPO ee gt Y eh Ge eget Lif Se j SA SY j j N Change plot3dQ for plot3d10 to get a different texture ANAM A different approach to this task is shown in Example 3 5 There is a bug in the script given in Help meshgrid t 3D graphs surf ask amp script Write a script that plots the function z 2 x2 y2 exp x 0 5 y where 2 lt x lt 2and 3 lt y lt 3 The function lin
12. Here it comes the lesson on MathCad that Jim gave me back in 1991 transformed to Scilab A lecture worth gold in three slides Scilab in 15 minutes 1 3 write a script Recall how Jim taught me MathCAD in 15 minutes Now we ll repeat that lesson in Scilab We do it by using the Editor SciNotes On the Console Click the leftmost icon on the toolbar The Editor pops up Define whatever variables your function needs row 1 Note comment Next define the sine function in case row 2 Finally write the plot command row 3 E Scilab Console File Edit Preferences Control Applications IE DO S Ag al a e O say N foo sce HADr EW Writings Scilab examples foo sce anrima File Edit Search Preferences Window Execute DEREmAAe X ELICEI Untitled 1 Ea foo sce A 0 5 x parameters 3 2 x equation ploty plot command Scilab in 15 minutes 2 3 save and plot Save the script by Clicking on the Save icon and name it e g foo sce Finish by running executing the script by a Click the Execute icon a second one came with 5 3 2 Up pops the Graphics Window with the a plot of the defined equation Did you have problems or get an error message on the Console Don t worry we ll return to everything later Jump to Examples 1 1 amp 1 2 if you are in a hurry amp Bb oN Sb OC LN wo EO Scilab in 15 minutes 3 3 discussion Thi
13. Opens text file rows size data_file r Determine number of rows readings data_file 1 Column 1 reading redundant outdoor data_file 2 Column 2 outdoor temperature indoor data_file 3 Column 3 indoor temperature Spreadsheet data 5 7 script for plotting 2 2 The plot command uses the obsolete plot2d0 syntax that we have seen before The reason for having it here is that plot2dQ with the frameflag argument of the new syntax does not work when two graphs should be fused into one plot The second plot destroys the first one and when the rect argument is included Scilab responds with an error message know it tried it Assume outdoor temp always lower than indoor and form plot commands ymin min outdoor ymax max indoor dy ymax ymin 10 Determine min temp Determine max temp Define frame margin Define plot frame rect 0 ymin dy rows 1 ymax dy x linspace 1 rows rows plot2d x indoor 5 011 rect Plot inodr temp plot2d x outdoor 2 000 Plot outdor temp xgrid 1 Add grid xtitle TEMPERATURE MEASUREMENTS Reading Temperature deg C legend Indoor temp Outdoor temp 4 Spreadsheet data 6 7 plot Simple plot but the main point with this exercise is to show how to go from spreadsheet data to a text file and then to plot the data TEMPERATURE MEASUREMENTS And then we turn to the question o
14. Q Return to Contents Windows installation 1 3 1 Download Scilab from 2 The right operating system www sScilab org should be on top Save the file Windows on the top typically it goes to your own other OSs below Downloads folder Home Scilab WebSite Molla Firefox File Edit View History Bookmarks Tools Help K lt H C fa http www scilab org BB Home Scilab WebSite SS support communities projects education Download Scilab Windows 138 MB w f N ez ia Windows installation 2 3 3 Scan the downloaded file for viruses 4 Double click on the file to install Scilab Inside the follow the prompts Downloads file ere ee eet Date modified Type Size Tags IE Documents 5 scilab 5 3 2 13 5 2011 18 52 Application 124 898 KB Mere Folders ip Desktop E Documents H Downloads E Favorites D isk d 1 item Windows installation 3 3 JB Setup scilab 5 3 2 5 Scilab suggests that it ee a carcanaat should install all toolboxes modules Go Select the components you want to install dear the components you do not want to for it unless you are install Click Next when you are ready to continue really short of memory 6 Accept Scilab license terms you have no option SO why do they ii em the scilab 5 3 2 Setup ask Click Next as el izar je rapnics duie Setup has finished installing sdlab 5 3 2 on your computer ma
15. Handles 10 12 demo step 5 Add gid gt _ BO Change x axis ticks amp marks a x_ticks tlist ticks locations labels Change y axis ticks amp marks 0 pi 2 pi 3 pi 4 pi 14 0 pi 2 pi3 3 pi 4 pi 14 Final 0 010 a y_ticks tlist ticks locations labels 0 5 0 25 0 0 25 0 5 e050 2500250 S COSINE PLOT 5 Note There were a O e enact anh A SAE CEN problems with ticks amp F i marks Only the S oo S E presented syntax Liy worked CUCO ee Db comments 1 2 With handles we must observe the order of Scilab commands For instance a script of the following type causes an error message from Scilab plot l error 15 Submatrix incorrectly defined legend alpha beta ceecee at line 6 of function h_get called by at line 16 of function generic_i_h called by a gcaQ abline 2ortanetion es h called by a children 1 foregroui tor lt i children 1 foreground 5 Sum vattern re at me 6 S orexet Tie Called by opulse_a pattern sce 1 The error message confuses by referring to a submatrix The real reason is that we try to change the color of the plotted graph after the legend was declared Scilab cannot jump back to the legend and change it The legend command has to come after related handle declarations But there exceptions Handles 12 12 co
16. beating sinusoidal tones t linspace 1e 2 1e 2 1001 To the right is a Matlab code top and its Scilab equivalent x cos 2 pi 1500 t cos 2 pi 1300 t bottom The way I did it m 2 cos 2 pi 100 t plot t m bi t m br t X K m Checked visually for differences axis 0 01 0 01 2 4 2 4 a title Beating between tones Comments I I xlabel Time SY Built in functions pi gt pi ylabel Amplitude Plot commands are split up on multiple rows Indents are not necessary but a visual help Changed what I could the run the script and let Scilab s debugger yell about the rest Checked frequently with Help particularly Matlab Scilab equivalents to understand the error messages on the Console Manual conversion 2 6 Case 1 plot There were some problems with this conversion I split up Matlab s long plotQ command but the abbreviated form did not work in Scilab First I changed Matlab s axis to rectQ then Swapped the preceding argument part for x m Now plot worked The label commands gave problems The reason was again that I had copied the Matlab code and the were pasted incorrectly 4 I iM i a 004 0 002 0 000 0 002 0 004 0 006 0 008 0 010 Time 5 il Fl u 2 at E Ed l 4 2 Manual conversion 3 6 Case 2 script amp plot m The pie functi
17. ode can also have optional arguments See Help for details First order ODEs demo Let s find the solution for the first order homogenous ODE x X T with the initial condition x 0 1 Plot the solution for t e 0 20 Start by rewriting the function as x x2 t Note how x is designated y in the deff argument davfdt x 2 t In this case Scilab does not accept numeric arguments of children Second order ODEs introduction m Scilab only supports first order Problem expressed as differential equations as do other second order ODE programs for numeric computing a Higher order problems must be Select state variables reduced to first order systems i e by shifting to state space Substitute state representation variables with zeroth m The methodology runs according ordai an to the algorithm shown to the right Rewrite problem as first order state space equation system Solve using Scilab s ode function A good treatment of state space methods is e g Chapter 8 in Burns R S Advanced Control Engineering Butterworth Heinemann 2001 Second order ODEs RLC circuit 1 5 the task The task is to plot the output voltage v for the shown RLC circuit when U 5V switch closes att 1 yal R 0 32 ns Al e D eh L 0 5 H C 0 8 F v t m We can derive the following second order ODE for the circuit d v t dv t LC RC v t v t dt dt 00
18. pi 2 pi 2 2 pi pi 2 2 pi 2 pil 1 5707963 1 5 707963 1 5707963 6 2831853 6 2831853 6 2831853 gt l err int2d X Y f err 9 805D 11 4 9348022 Numeric integration 5 6 double integral plot f x y y cos x x sin y with O lt x lt pi pi 2 lt y lt 2 pi The plot of f x y y cos x x sin y is here done with a separate script The figure has been edited with the Figure Editor Numeric integration 6 6 double integral check m We can check the computed result using the other possible triangulation Now we get the triangulation matrices shown here m Plugging these matrices into the Console gives the following result gt X 0 pi 0 pi pi OJ gt Y pi 2 Ypi 2 2 pi pi 2 2 pi 2 pi gt l err int2d X Y f err 9 887D 11 js Same result but a small difference A in the estimated error 4 9348022 Ordinary differential equations ODEs ode a This simplest call for solving ODEs is ode that has the general form y ode y0 t0 t f t y where yQ initial condition normally a column vector tO initial time normally 0 t vector of instances for which the solution has to be computed e g t 0 0 01 10 f t y function for which the solution has to be found often stated as yoo f t y Here t is a scalar y a column vector and ydot a column vector with values of the derivative
19. Polynomial seed The first two gain equat Gain1 syslin c s 2 20 s 100 s 2 6 s 100 are given as ordinary Gain2 Gain1 syslin c 5s 2 3 s 220 s 2 25 s 225 Gain3 poly 5 s poly 0 0 2000 200 25 1 s c Gain4 syslin c 352 Gain3 The third gain equation Bode plot ER oe be used in plotting Evans Pee KoPA iSe alcoi cainplot Gain2 Gain1 0 01 100 Magnitude plot its roots Nyquist plot Pape pe a eee The Bode plot is only wee subplot 222 gain later the alterne nyquist Gain2 Gain1 Plot with Re and Im axes bode will be demonsti Nichols chart Black s diagram iso plots Scilab talks about Black La a a N diagram rather than Nich black Gain2 Gain1 0 01 100 Gain2 Gain1 orle eeano eea aeae lala chart 8 6 4 20 50 80 list 1 0 5 the difference between the OIE ee two Se subplot 224 evans Gain4 100 Evans root locus for sys4 Ex 3 1 plot The plot has not been edited everything shown is the result of the script Note the red iso curves on the Bode Nichols 2 D 0O 15 20 25 30 35 subplot Aa Evans root locus M T 3 CENTI looks at how 1 p asymptotic directions alternative Bode o plot commands operate Magnitude Db Imch 2i pi Magnitude Db Imaginary axis 15 1 00 80 60 40 20 O 20 40 60 80 100 ar 10 5 Phase deg Real axis Ex 3 1 alternative Bode imn fun
20. pi 2 pi 2 18 18 steps vertically hp linspace 0 2 pi 36 36 steps horizontally mS 2 Planet radius Ex 6 6 planet amp moon flasks 2 3 Moon m 20x20 degree grid amp offset from origin vm linspace pi 2 pi 2 9 9 steps vertically hm linspace 0 2 pi 18 18 steps horizontally m Basic variables for the o oS oe bose m 21 oon offse NOON j both for the Az 0 Moon start point moon itself and its n i of moon revolutions location in space step 100 of steps revolution Define facets for spheres using subroutine facet GO TO subroutine Ge facetQ to compute Xp Yp Zp facet vp hp Planet facet matrices Xm Ym Zm facet vm hm Moon SAA Plot commands box planet moon Basic plot definitions Define 3D box put double buffer on define surface a gca a data_bounds 5 5 3 5 5 3 3D box size f gcf f pixmap on Double buffer f color_map hotcolormap 32 Surface color Ex 6 6 planet amp moon Tol a 9 at CYC Loop for rotation begins Delete old graphs Put color on the box Push planet data to first buffer Recalculate moon location amp push data to first buffer show_pixmapQ push plot to screen Plot planet amp rotating moon for Az 0 2 pi step n 2 pi Delete previous entities planet amp moon if a children then TF frame contains graph delete a c
21. wi Second order ODEs RLC circuit 2 5 reduce Simplify the equation for clarity LCv ROY a Select v and its derivative v as state variables and substitute E a x v x m With v substituted by u the first order ODE system becomes x Ox 5 exo a O simpler x xX l l R j xa 30 1 ae Wes m Which gives the state space expression that we are looking for ae O l X O Ii 1 R J ju Xo 7 Xe RC R ine Second order ODEs RLC circuit 3 5 script Recall the discussion in connection with Ex 2 3 We are working with a matrix expression of the type x Ax bu All of these factors can be seen here with x being denoted ss and x substituted by y RLC_ODE sce Simulation of a series RCL circuit with 5V step input voltage at t 1s clear clc clf Define circuit components R 0 3 L 0 5 C103 Resistance Ohm V A Inductance Henry Vs A Capacitance Farad As Define space state equations amp input signal A 0 1 1 L C R L B 0 1 L C deff ut u t ut 2 5 1 sign t 1 Step input signal System matrix Input matrix deff ss RLC t y ss A y B u t Space state expression Second order ODEs RLC circuit 4 5 script The ode function computes our differential equation by using the RLC state space expression of the second deff function Call
22. A ee SNNN a 4 a ee i ae a a te LPF oe ae x Faa a ae ee NON O VOA f gf 2 f PE ae oa Mixed contours and vector fields Vector fields are not very informative per se but the situation improves when they are fused with contours In the previous case just insert the champ and contour 0 commands into the same script and you get them in one plot X t x x lt x Cutting a 3D surface m We can see the outline of the 3D surface z 2 x y2 exp x 0 5 y2 at a certain plane by defining the plane in case below y 1 and by returning to 2D plotting 0 3 0 2 0 1 0 0 0 1 0 2 0 3 0 4 05 0 6 0 7 2 0 1 5 1 0 0 5 0 0 0 5 1 0 1 5 2 0 Mixed 2D 3D plots 1 2 script Scilab has its own ideas of what it should do if a contour command is added to the script of a 3D plot command plot3dQ surfQ Trial and error is needed Question Should contour come before or after plot3dQ Answer Scilab accepts both alternatives but with dramatically different results Only the first flag argument of contour has an influence on the plot plot3d contour sce Plot the combined 3D graph and contour of the function Z 2x42 y 2 exp x 2 0 5y 2 for 2 lt x lt 2 and 3 lt y lt 3 i clear clc clf x linspace 2 2 30 y linspace 3 3 30 X Y meshgrid x y Z 2 X 42 Y 2 exp X 2 0 5 Y 42
23. Artech House 1991 AF sin T sin Ex 3 4 beam scanning The previous expression for AF is valid when the beam is normal to the array axis Scan angle broadside case If the beam is deflected the scan angle 8 must be included in the equation gt AF sin Nr sin Q sin 0 sin T sin 6 sin 0 In a more complete simulation we must also include element factors tapering and mutual coupling between the array elements Scan angle attay_factor sce Plots the array factor of a linear antenna array with N elemnts spaced at d wavelengths and main beam scanned at 60 degrees clear clc clf Variables eee i N 10 Number of radiating elements This script is for the di 0 45 Element spacing in wavelengths Tele assjon fol d2 0 55 Ditto pI EVIOUS SAPE a for theta pi 2 0 01 pi 2 Half space 90 deg AF but normalized theta_z pi 3 Scan angle divided by N to keep Define array factors the main beam value at Sm f_phase1 pi d1 sin theta sin theta_z Phase function it hac TAAS f_phase2 pi d2 sin theta sin theta_z Ditto RA PR ee a ae Normalized array factor d 0 45 j aly in AF_norm2 abs sin N f_phase2 sin f_phase2 N sills peek y a Normalized array factor d 0 55 eee Orm Plot functions expression for AF_norm Subplot 211 Line
24. Color definitions Call subroutine Geta create_sectors rad angle width colors END MAIN Ex 6 4 sector chart plot Here is the plot nice and beautiful We can Suppress the axes by changing the plot2d0 argument 031 to 030 COLORED SECTORS The overlapping yellow sector just happens to be on top last element in the vector list In practical applications when doing automatic plotting of some process we would have to put more effort 46 into getting the plot the 10 0E C 04 02 00 02 04 06 O8 10 way we want Example 6 5 Robot arm 1 6 introduction Recent web discussions on the relative virtues of Scilab Matlab and Octave made me take a new look at manual conversion of Matlab scripts m This case with a two dimensional gt moving robot arm is from Chapman ros S J Matlab Programming for are Engineers 2nd ed publisher amp X year unknown pp 202 206 The case demonstrates practical application of matrices See Chapman for a full discussion Base motor m The original script can be found on a Hand the next slides the converted script Se with added comments are on the following two slides Ex 6 5 Robot arm 2 6 Matlab script a Robot arm motion script Initial values angles in degrees tf 2 theta10 19 pi 180 thetaltf 43 pi 180 theta20 44 pi 180 theta2tf 151 pi 180 Equations
25. Declaration of initial plot in GUI function initial_GUI t linspace 0 7 200 w 5 Initial angular frequency plot2d t sin w t rect 0 1 1 7 1 1 a gca a axes_bounds 0 2 0 8 1 Frame dimensions amp location xtitle GUI DEMO WITH sin wt Time s Amplitude a font_size 3 a xX_label font_size 3 a y_label font_size 3 a title font_size 3 endfunction Initial plot w 5 rad s Axes mark size X_label size y_label size Title size E 6 1 5 Functions for changes wrt user actions E Oaa aaa X E uuu function update _slider TF slider movement new_GUI_data GOTO new_GUI_data S C ri t 4 endfunction p E E function update_radio IF radiobutton click iia 4 new_GUI_data GOTO new_GUI_data The next two ieee endfunction 0 ecole Lee O CRON Redefine plot in GUI EROICE COOGEE and radiobuttons E a respectively and point a errariaaial to the fourt subroutine a gca drawlater Delay changes new GUI dat a 3 if a children then IF frame contains graph delete a children if end erased P plot2d t sin w t radiobutton has been end cl j cked drawnow endfunction then delete graph URC No OR w slider value 10 Slider range 10 steps if h_radio1 value 0 then Check status of style butt
26. End of plot t linspace 0 fin 1000 A 2 exp t s A sin w t 10 t 2 phi f_mom f 10 t Momentary frequency plot t s r t f_mom b xgrid xtitle SINUSOIDAL PLOT t legend s f_mom 2 Ex 1 2 final plot OK not an optimal plot but the information is there With the big differences in vertical scales we should either use logarithmic y axis or separate the two into but that comes later SINUSOIDAL PLOT Pay attention to the legend Ex 1 2 discussion m As was Said earlier Scilab evolves with time and approaches Matlab with each release m As an example in case Scilab s Help Browser recognizes the xlabelQ and ylabelQ that I used in the improved plot as Matlab functions and also refers to them as Scilab functions However there are plenty of obsolete Scilab functions and you find them all over if you rely on old tutorials Even Scilab s Help Browser may refer to them Be careful particularly if a function name begins with x cf note in Chapter 7 a You may have noticed that I begin the script with a comment stating the name of the script e g modulation3 sce I do this to help identify the script when I am looking at a printout Example 1 3 Lotto the task The first part of this example is borrowed from Makela s tutorial Task 1 Create a user defined function UDF that draws a row of Lotto numbers Assume that the L
27. Find the solution to x in b Editor and named d i algebra1 sce A 1 2 1 2 6 4 1 3 3 algebral sce b 1 2 1 Note the x A b Backslash Operator The solution Xi TA 2 X 2 algebral sce has to be run from the Console since the script contains no disp command gt exec algebra1 sce gt algebra1 sce gt gt Find the solution xin gt Ax b gt Asno ZPS 2i gt x A b X ors 2 2 Ex 2 1 checking the result It is good practice to check one s solutions In this case it can be done by making sure that the residual B Ax is exactly zero m The altered code is renamed algebral_check sce and saved before being executed The result is 0 as hoped for note that there is no rounding error here the result is exactly zero algebrai sce Find the solution x in Ax b A 1 2 1 2 64 1 3 3 b 1 2 1 x A b algebra1_check sce Make sure that b Ax 0 residual b A x Ex 2 1 what should have been done before Problem The determinant of the coefficient matrix A must be non zero E gt A 1 2 1 2 6 4 1 3 3 ue In line with what has been said earlier we should start by E that the determinant of the coefficient matrix A is nonsingular ton Scilab would have yelled if that had been the case We can test it in hindsight and see that th
28. Interfaces for Fortran Tcl Tk C C Java Modelica and LabVIEW but not for Python and or Ruby a Which is better Matlab or Scilab Matlab outperforms Scilab in many respects but Scilab is catching up The use of Matlab is motivated only in special circumstances due to its high cost Why use Scilab personal reasons Matlab 6 5 R13 was not compatible with my new Windows Vista laptop MatWorks Inc recommended to buy a new version I refused to pay another license fee for Matlab and went looking for open source alternatives Sage felt bulky immature and focused on pure mathematics Python is not optimized for scientific and engineering tasks Python x y messed up my PC when I installed it Maybe I should I have tried SciPy instead I grew tired of GNU Octave before I figured out how to download and install it I want a tool to use not to fight against Scilab was the fifth alternative that I looked at It gave no immediate problems so I stuck to it Later I have come across bugs and crashes lockups and become frustrated with its poor documentation Why people don t use Scilab The following are some comments about Scilab and open source software in general that I have come across e Scilab Never heard of it e Octave is closer to Matlab e As a company we have to use software that will be supported ten years from now e It doesn t have the toolboxes that we need
29. Unique rows are that was discussed earlier a aia A few more functions 4 5 rand We have seen the random number generator rand several times already m rand can generate two subplo types of numbers either nIStDOH with oli distribution Uniform is the default Gaussian normal is selected with the argument normal or n To the right are histograms of 2000 random numbers generated with uniform and Gaussian distribution the latter with mean 0 variance 1 A few more functions 5 5 grand The function grand0 is than randO It allows most existing distributions to be generated Shown here is an example with Chi square exponential and Poisson distribution histograms be a ee a A pee ca A d 0 2 4 6 8 10 12 0 2 4 6 8 10 12 0 2 4 6 8 10 12 Johnny Heikell 6 Examples Set 2 Adds to what we have learned so far Q Return to Contents Example 2 1 solving an equation system The task is to solve the following system of equations x AX mage Sony 6X 4x Shon oe We can write it in the matrix form Ax b where Next we set up the equations in Scilab to find the solution x Ex 2 1 script amp solution The code for the equation system as entered in eee
30. can call other subroutines Nested subroutines m Subroutines can be nested if it is worth the added complexity gt function y dalle The example shown here computes the a equation y x sin x 2 pi 2 sqrt sin x 2 pi 3 gt gt function y inner x gt y x2 sqrt x gt gt endfunction y inner a 3 2 27 ee a gt endfunction in three steps First sin x 2 pi is Pa calculated The result is then squared and subtracted with the square root of itself 57 437413 Finally 3 52 9 is added m Plug in the equation in a gt sin pi 3 2 pi 2 sqrt sin pi 3 2 pi 3 2 calculator and yes it gives RRF the same answer I prefer P this old fashioned method R The deff primitive a The deff primitive can be used to define simple functions it resembles Matlab s inline function deff is therefore used in local subroutines The syntax is deff Cy function_name x1 x2 y function expression Below is the same equation computed on the Console with function and deff alternatives a Note the semicolon gt g 2 g 5 Scilab ai understands if you skip it after the second y expression gt deff y f x y x 2 x 1 gt function y g x y x 2 x 1 endfunction gt f 2 5 ans Global subroutines window demo 1 4 T Figure Editor Graphic Edit This demo creates a global Obes Bow
31. controls tne style O Jj anaaneeceren ener erereranaa annarentonna j h_radio1 uicontrol h_graph ee He pls style radiobutton Declare radiobutton Min 0 default turns to a bar MaCs yalue 0 Initial button value ToDo s ked backgroundColor 1 1 1 radiobutton is clicked position 10 size_y 350 20 20 callback update_radio GOTO to update_radio The commands are h_text_radio1 uicontrol h_graph quite simil ar to the style text Reheat Declare button text horizontalalignment left ones of the Slider string Change graph style except that the foo backgroundColor 8 8 8 Gray background command is missing tonisize Lee position 40 size_y 350 140 25 Field size amp location Notice the callback statements They are the beasts that make us jump up to GOTO the subroutine in case here to update_radio Q Ex 6 1 user defined GUI Bac 6 6 The second Add radiobutton for graph color fe ana es eas ae ae radiobutton controls h_radio2 uicontrol h_graph the color of the style radiobutton Declare radiobutton plotted sine curve es black is the default Hoa acK IS e default yalue 0 Initial button value turns to blue when backgroundColor 1 1 1 i j i position 10 size_y 380 20 20 radiobutton is clicked callback update_radio GOTO to update_radio s o h_radio2_txt uicon
32. gt y2 myfunc 4 7 y2 12 3x4 12 gt y1 y2 myfunc 4 7 y2 37 5x7 2 37 With no output argument defined the first output argument is returned in the ans variable The same answer is returned when only one output argument is defined With both output arguments defined the result of the computation is returned in full Vector arguments a This function uses The function is first defined After that the output arguments the operations to do are defined Next the input arguments row vectors are entered At the end the function is executed The in line function deffQ is a specialized form of local functions gt x 1 gt x 2 gt X 3 gt endfunction gt Define local subroutine cross_product gt function x cross_product a b 2 b 3 a 3 b 2 b b a a 3 a 1 3 1 a 1 b 3 b 2 3 1 b 2 a 2 b 1 gt Plug in numeric values gt a 2 5 8 gt b 7 13 5 gt Executing the subroutine gt C_prod cross_product a b C_prod 79 x 1 5 5 8 13 46 x 2 8 7 2 5 9 x 3 2 13 5 7 Here I use the term function since the code is independent and not called by a main program Demo 1 2 script Compute amp plot a parabola find its positive root Here the subroutine is called for the first time using the input argument x Here the subroutine
33. is nonzero Consider the following cases F J 6 3 2 5 8 itis therefore nonsingular E 1 6 1 3 2 0 meaning that it is singular Earlier we found that Durer s magic square is singular so is e g the matrix A 123 456 789 Before performing left division with square matrices one should check that the determinant of the coefficient matrix is nonzero e g by testing that clean det A 0 Strings 1 6 they are matrices too Character letters text special characters strings can be created by using single or double quotes This is a amp ck2 string and so is this Typical use of strings is in plot commands to define the title and x and y labels Other uses are interactive inputs and outputs inputQ dispQ etc and write commands write io 2 Strings are considered as 1x1 matrices scalars in Scilab but mixed character numeric strings are typically 1x3 matrices It is shown on the next slid with the command disp Was it string a that you said Elements 1 2 3 Example 2 4 shows an additional application of strings Strings 2 6 disp string The most usual string display command is disp where the gt a 125 text has to be in quotation ee ees ier marks disp text or gt disp Was it string a that you said disp text Was it 125 that you said m can be added to disp but has to be using the man functio
34. the cone should have different shades Objects are manipulated by vectors created by the earlier user defined functions STEP 1 CREATE amp PLOT BASIC CONE Superimpose rectangular facets xv yv zv eval3dp cone linspace Y pi pi 20 1 10 f gcf Get Current Figure create figure f color_map graycolormap 32 Select color Plot basic cone with tip at the origin plot3d xv yv zv el gce Get Current Entity handle el1 color_mode 24 Object exterior light grey e1 hiddencolor 30 Object interior dark grey I STEP 2 MANIPULATE amp PLOT OTHER CONES Object manipulations parameters XYZ xv syv ZV XYZ 3 x N matrix XYZT translation 1 3 3 XYZ Lateral shifts XYZH homothety 5 7 3 1 5 1 1 1 XYZT Non dilational rotation XYZR rotation 15 15 30 XYZT Rotation Ex 4 2 script 4 4 Plot another cone this one is zoomed up and sifted laterally Same Shading as before And the third plot with the cone shifted laterally and rotated Shading as before Properties of the box around the cones is adjusted Isometric scaling is on check with Help for an explanation Plot second cone enlarged M plot3d matrix XYZH 1 4 1 matrix XYZH 2 4 1 matrix XYZH 3 4 1 e2 gce e2 color_mode 24 e2 hiddencolor 30 Get Current Entity handle Object exterior light gre
35. 166 m The script is quite complex with four subroutines and three separate plotting structures which makes it difficult to follow the transfer of parameters Changing an argument can have unexpected consequences Some aspects of the script have not been covered before and will be left without detailed discussion here as well see however Ex 4 3 The object a cone the book mentions and shows a vase is plotted in three separate positions using lateral shifts rotation and non rotational dilation homothety of the objects m The cones are shaded using handles that are called through the gce command Scilab functions used for the first time diagQ eval3dp0 graycolormapQ isoviewQ sizeQ Ex 4 2 script 1 4 verticall tells how to move along the z axis in later calculations Note the increasing and decreasing values that will cause for shading m The function coneQ generates the cone in case Example 12 discusses how it is done cone_manipulation sce i a en to ar ah ee ey The script generates and plots a cone with its tip at the origin It plots two copies of the cone one shifted and one shifted amp rotated Te ea AE AE EA Socal A Ss eu aa ce ae aa clear clc clf Vertical reach of 3D object vertical 0 1 0 1 6 2 5 2 2 2 1 6 0 9 0 5 0 3 0 3 0 4 0 6 1 1 4 1 7 0 0 0 1 0 4 0 8 1 1 1 4 1 7 1 9 2 2 2 49 7 3 3 3 3 7 3 9 2 SUBROUTINE 1 Generation of 3D object function
36. 3 the plot The plot is very basic as it has Graphic window number 0 m Eile Tools Edit We ll return to them in the zlaalcle next example E S The abscissa scale may seem strange the maximum value for x was 10 but the scale goes to 100 The figure 100 is actually the number of calculations since they were made in steps of 0 1 up to 10 Try to change t to x 0 0 2 10 and you ll see that the scale ends at 50 the modified script must be saved before it can be run 5 4 3 2 1 0 4 2 3 4 5 Ex 1 1 comments 3 4 cif Assume that we make a change to the script e g increase the frequency to sin 5 s save it and execute it immediately after a previous run Graphic window number 0 File Tools Edit Saa Ele As a result Scilab 5 4 3 2 1 o 1 2 3 4 5 To avoid this we must either e Close the Graphics Window manually after each run or e Add the function clf clear figure to the script to make Scilab clean the window Ex 1 1 comments 4 4 cleaning trash Some programmers prefer to safeguard against different pees forms of A simple 2D plot of a sine function e i with the abscissa x 0 10 the script To do this three and amplitude A increases with x commands are added at the ps aaa a beginning of the script dlear cic df gt x T6 r Tt The abscissa x is a row vector A 057 Modulated amplitude row vector
37. Funcall EN m2sci_abs Absolute value and complex magnitude Cl ick on the fi rst i ie Infer m2sc aa Inverse cosine 1 ms i 4 Matlab Scilab_character_strings r n Inverse hyperbolic cosine subheading VEED H Cesena r iese cotangent i ope Type r Inverse hyperbolic cotangent Scilab equivalents and pe Variable Inverse cosecant A p get_contents_infer r Inverse hyperbolic cosecant you g et a ist of M atl a b i m2scidecare Test to determine if all elements are nonzero 4 i E i ie matfile2sci r igle Phase angle i ie mfile2sci r ny Test to determine if any nonzeros elements functions and their Scilab piaig mgec_ary Testo determin equivalents missing ones translatepaths r Inverse hyperbolic secant 3 Compatibility Functions r Inverse sine Maple Interface r Inverse hyperbolic sine Overloading r Two quadrant inverse tangent Functions f Ei Four quadrant inverse tangent Development tools O m2sci_atanh Inverse hyperbolic tangent Ai Demo Tools m are not included like textQ and xlimQ mentioned below 8 BE EB BB Using the integrated Matlab to Scilab translator Scilab can convert Matlab s m files to sci files although we should not expect the conversion to be fully successful every time The translated script may have to be modified manually We start by opening the translator EE Scilab Console On the Console Click Trae A Applic
38. Z 2 KF 2 72 rexp X 2 0 51Y 2 subplot 223 champ x y X Y x linspace 2 2 50 y linspace 1 1 0 X Y meshgrid x y 227 2 1 2 exp A 20S 2 subplot 224 plot2d x Z 5 Note that only the plot function has been repeated for 222 subplot demo plot 0 8 0 6 z 02 x 0 0 There is 02 another 05 function for subplots 141 5 10 05 00 05 10 15 20 xsetech 0 3 0 2 0 1 0 0 0 1 0 2 0 3 0 4 0 5 0 6 Check with Help for details N YA BE a tere he l ergs reese 2al TETE t 4 l J l t PERT amp we Liara NNN v k a NA N aa CEF ag 1 fi f f 0 7 1015 20 25 20 1 5 10 05 00 05 10 15 20 2 5 2 0 15 1 0 0 5 0 0 05 plot2d2 plot2d3 plot2d4 demo script m The plot2d function has three variants m plot2d2 for step functions m plot2d30 for vertical bars ms plot2d4 for arrow style lines The effect of these plotting commands on the sinc0 function is shown on the net slide plot2dx sce Demonstration of the basic sinc function plotted with plot2d plot2d2 plot2d3 and plot2d4 clear clc clf x linspace 10 10 50 subplot 221 plot2d x sinc x style 5 Plot continuous line xtitle plot2d subplot 222 plot2d2 x sinc x style 2 Plot with steps xtitle plot2d2 subplot 223 plot2d3 x sinc x style 2 Plot vertical bars xtitle plot2d3
39. Z A S 22223 31233 A tes a2 ie 21 22 23 31 32 33 JA11 12 19 21 22 23 31 32 33 Note Scilab may cause a copied screen A text as seen here to be underlined i ae 4 when pasted to another document If Ali 22 20 de tee so put the cursor at the end of the text Bute ee and press Backspace Row and column vectors Task 1 Create a row vector with first element 0 last element 1 and E increment step size 0 2 tt ii Eroa order and colons that divide 0 0 2 04 06 08 1 elements Task 2 Create a similar column V NO A E A a_a oo ar column signifies the matrix transpose 0 0 2 In case the Console window is set 0 4 too small and all elements do not ees ne fit in Scilab interrupts plotting and i asks if it should continue Some special matrices 3x3 identity gt C eye 3 3 matrix us 1 3x2 matrix of ones 2x3 zero gt E zeros 2 3 matrix E 0 0 O 0 0 O The function rand m n creates a mxn matrix Adding the argument normal creates a gt rand 4 4 ans 0 2312237 0 2164633 0 8833888 0 6525135 0 3076091 0 9329616 0 2146008 0 312642 gt rand 4 4 normal ans 1 8772844 0 7915156 0 1728369 0 7629083 0 6019869 0 0239455 1 5619521 0 5637165 0 3616361 0 2922267 0 5664249 0 4826472 0 3888655 0 6594738 0 6543045 0 6773066 matrix 0 3321719 0 59350
40. a collection of buttons Click on any of the pieces next to the space and that piece will slide over the space Continue this until the pieces are arranged in numerical order from upper left to lower right Sound file handling Random Dismiss Scilab the Spy meem Fie Edit Preferences Control Applications T ECE 0 biasia e ee E aio COLMO a AE AA l r 3 Bibonacci 3 a fibonacci 4 365 3 fibonecci i0z4 f f Begin Session Fri Mar 22 18 51 20 2015 gt fibonmecoi 32 382 exec fibonacci 32 Software that we install on our fiso eatoneces 32 computers tend to spy on us by fi5z i rinenaeei 32 collecting information on what we 34 Sanaa do Have you ever cared to figure 96 ranavane sos out how much data e g Windows maip break index dat has stored about your ie a computer amp surfing behavior Di AE w gt 6 en Scilab spies with at least its poe OF history manager You can access gop t tn this data by entering p30 creek Err displayhistoryQ on the Console 252 s ema The file can be cleaned via P Preferences Clear History Sorry I could not copy paste an extract because PowerPoint crashed repeatedly it happens to Bill Gates as well Often Johnny Heikell 4 Examples Set 1 Demonstration of basic Scilab p
41. add the following command to axes_visible on on on the script axes_reverse off off off grid 1 1 grid_position background xtitle COSINE PL T x_location bottom X axis ra y location AeIE i title Label x_label Label And now the has y_label Label undergone a dramatic change this a ee T IS only the beginning of the list x_ticks locations 0 2 4 6 8 10 12 14 y_ticks locations matrix 11x1 z_ticks locations x_ticks labels 0 2 4 6 8 10 12 14 y_ticks labels matrix 11x1 z_ticks labels Handles 9 12 demo step 4 Title and axis labels have been added the next step is to edit them In each case we must lle or skip this stage by writing editing commands in the form a title font_style etc then edit the handle properties Check for details under label_properties in the Help Browser The plot isn t exactly a beauty but we ll add a grid and edit axes ticks amp marks xtitle COSINE PLOT X axis Y axis t a title t font_style 5 t font_size 3 xL a x_label xL font_style 5 xL font_size 2 yL a y_label yL font_style 5 yL font_size 2 Add title amp labels Get title handle Times bold italic Increase font size Get x_label handle Times bold italic Increase font size Get y_label handle Times bold italic Increase font size COSINE PLOT
42. are written in plain style 1 but a shown in earlier demos the number alone is enough Ga os 08 10 12 14 18 18 fplot2d m fplot2dQ is a variant of plot2dQ With fplot2dQ a function and its definitions can be included in the arguments The general form of fplot2d is fplot2d x f opt arguments The demo to the right shows a case where xX linspace 10 10 100 f Scilab s in built sinc function style 5 is an optional argument There is also a 3D alternative fplot3d0 x j gt fplot2d linspace 10 10 100 sinc style 5 opt arg plot the beauty of simplicity 1 2 Bi Scilab s plotQ function offers a simpler way to distinguish between multiple plots than does plot2dQ It is by using keyboard characters the way it was done on teleprinters half a century ago ee Here three graphs are plotted with one plot command The style definitions are o x and lt Note that t is repeated for each graph It can be seen that lt red gives a triangle that points in the direction of the path of the line Scilab s plotQ function does not support all properties of its Matlab counterpart plot the beauty of simplicity 2 2 The following list contains main line style codes for plotQ cc ec Seco Dotted ine diamond or Diamond panom A a o fom p eom r ee Color arguments are k Black w White r Red g Green b Blue c
43. be changed e g the ones shown here Check Help Color management colormap for more alternatives coppercolorma hsvcolormap PP pO hotcolormap alpha as yy ai ty i is Ai Example 3 6 Lissajous figures task The task is to write a script that generates Lissajous figures and to edit the figure with handles Lissajous figures are familiar to all who have worked with an oscilloscope in high school physics lab Mathematically Lissajous figures are the graph of a system of parametric equations of the type x A sin a t y B sin ot We shall plot two figures in one window the combination of sin x amp cos 3x and sin 1 5x amp 0 5 cos 1 5x For comparison we first do a basic plot with plot2dQ and then modify the figure with handles Ex 3 6 Lissajous figures script 1 m Sine and cosine functions are grouped into matrices m The plot2dQ argument 2 5 defines graph colors m The argument leg defines the legend a The argument nax defines axes divisions The argument rect defines the extension of x and y axes handles_demo2 1 sce Two Lissajous figures sin t amp cos 3t and sin 1 5t amp 0 5 cos 1 5t with plot definitions given by arguments of the plot2d function clear clc clf t linspace 0 6 100 sines sin t sin 1 5 t cosines cos 3 t 0 5 cos 1 5 t plot2d sines cosines 2 5 leg sin t cos 3t sin 1 5t 0 5 c
44. buttons or menus created by unsetmenu addmenu The numeric gwin argument if present tells on which Graphics Window the button should be installed m The button argument is a character string that defines a shortcut on the menu bar Tailoring windows 2 3 Optional arguments are submenus character string with names of submenu items action definition list of the type action list flag proc name This is not the whole truth The book by Das which is a collection of Scilab s Help function texts contains more hints As a demonstration of the above said here is a command that adds the menu Graphics with submenus New Window and Clear Window to the Console s menu bar Create gt addmenu Graphics New window Clear window Close window gt Graphics scf clf xdel BB sciiab Console Graphics Pa o_O OS o e File Edit Preferences Control Applications Graphics Iscf clf xdel 26 G0 mageng New window Clear window Close window Tailoring windows 3 3 You can convince yourself that the added Console menu works by clicking on New window to open the Graphics Window and click on Close window to close it again H As the following steps we can deactivate the created menu by the command unsetmenu and delete it with delmenu File Ed Edit Brees Control Applications Graphics COB Aalelg E Scilab Console File Edit Preferences Control A
45. crashes amp lockups Processor loads of this magnitude are normal during computer startup However this is the situation after Scilab had crashed and I had closed it WScilex exe had another of its lockups and required to be closed with the Task Manager or by rebooting the computer The Scilab team s standard answer to problems like this is to make sure that the computer s drivers are up to date It has not worked for my Windows Vista PC Manag iew Help Physical Memory Usage History Processes Intro to problems 2 3 new releases m With Scilab 5 2 came a problem that I did not experience with version 5 1 1 Copy pasting from Scilab s Editor to PowerPoint frequently caused the latter to crash The bug has been fixed a With Scilab 5 3 0 I found that the paths File Open file in and File Save file in on the Editor were unresponsive Some scripts that I originally wrote using Scilab 5 1 1 did not work with Scilab 5 3 0 and GUIs on 5 3 2 are a real pain down there Typically larger updates come with bugs and are quickly followed by minor bug fix updates a k a patches Scilab 5 3 1 emerged within three months of 5 3 0 This is universal in the software business m Itis wise to keep an old Scilab version until you know that the new release can be trusted I was happy I had kept version 5 1 1 when GUIs on 5 3 1 am
46. data Any input parameter except u d or e give an error message The break command works well in this case Homework Modify the script by using the select case else end structure instead of if elseif else end Which solution is simpler 1 Exit e Up u Down d u strg u 2 Exit e Up u Down d u strg u 3 Exit e Up u Down d d strg d 2 Exit e Up u Down d 6 strg 6 incorrect input 2 Exit e Up u Down d u strg u 3 Exit e Up u Down d e strg e you hit e Exit 13 Doing math on Scilab Scilab contains functions for sophisticated mathematics We ll 4 stay with the simpler cases B Q Return to Contents Math Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 in earlier chapters Complex numbers vectorized functions polynomials Trigonometric functions random functions Matrices matrix operations matrix operators symbolic computing random generators Linear equation systems with real coefficients 2D and 3D functions vector fields histograms rotation surfaces logarithms polar coordinates Polynomial expressions Application of matrices amp trigonometric functions Arithmetic and algebra Logical expressions Step functions application of 3D vector spaces optim amp fsolve demo 1 4 the task a The funct
47. different but serves the same purpose m As shown to the right gsort E picks out matrix elements in decreasing order and returns them column by column 0 2 5 We achieve Matlab like sorting by adding the arguments r row and y increase to gsort gt matr 1 4 2 2 1 0 3 3 4 5 0 5 gt Mtlb_sort gsort matr r i m Check with Help for details on Mtlb_sort arguments H ODS Be SB ee ee Be 0p 8 testmatrix Magic squares of different sizes can be produced with the testmatrix magi n function It is the same as the magic n function in Matlab Additional matrices that can be produced by the testmatrix function is testmatrix frk n which returns the Franck matrix and testmatrix hilb n that is the inverse of the nxn Hilbert matrix Check with Help for details gt testmatrix magi 4 13 12 gt testmatrix magi 5 te 6 13 20 2 9 2i 2 WSs 2512 bat 16 22 3 9 det M amp rounding errors m Practical problems often require the determinant of a Square matrix to be calculated The command det returns the determinant The determinant of Durer s magic Square is zero the matrix is singular but as shown the rounding error prevents Scilab from returning the exact answer recall that we encountered this problem before To get rid of the rounding error we can use the clean function It returns
48. disadvantages E Numeric computing introduces rounding errors contrary to symbolic computing m The learning effort required by numeric computing is higher than for symbolic computing Scilab lacks a unified tutorial and or user s manual You try and cry and waste time searching for information on its use In some cases Scilab executes much slower than Matlab and GNU Octave improvements are said to be under way Scilab s tools for creating GUIs are poor compared with Matlab The Help Browser is very formal and of little use to newbies Scilab has bugs and tends to crash lockup it happens to Bill Gates as well Often On line support from Equalis costs 495 or more per annum the French prefer to Terminology function The C programming language brought confusion with its unrestricted use of the term function and this is repeated in Scilab The term refers to at least e Mathematical functions in general e Scilab s built in functions e User defined functions UDF I would prefer the terms function macro or procedure and subroutine respectively protests form dogmatic programmers are overruled Sometimes I talk about subroutine but it is not always possible For instance function is the term that must be used to define a UDF in Scilab And there is also the risk of adding to the bewilderment by applying own terminology The confusion remains Intro to problems 1 3
49. elseif else end demo The following function computes the n th term of the Fibonacci sequence when n is given Save the script load it fibonacci sci into Scilab on Editor Gives the n th term of the Fibonacci type on the Console the sequence 0 1 1 2 3 5 8 13 function name with the ment Hint funcprot 0 Suppress redefenition warning ae t t l function K fibonacci n l if n Begin if elseif else end K 0 elseif n Condition to proceed n gt 2 K 1 elseif n gt 2 amp int n n Check if nis an integer gt 2 K fibonacci n 1 fibonacci n 2 Compute Fibonacci else Previous conditions not met disp error input is not a positive integer Error message end End of if elseif else end Check wh at endfunction happens forn lt 1 gt fibonacci 8 ans 13 select case else end m The select case else end construct executes the first case that matches the stated condition If no match is found it executes the else statement The advantage of select case else end is that it allows us to avoid multiple if statements Hint Use select case when if elseif else threatens to become too complex select condition case 1 foo case 2 Note select case is called switch case in Matlab may be changed in Scilab Y Xo R or E 0 e F demo script Some textbooks on Matlab pres
50. file handling e g to process measurement data Q Return to Contents File handling introduction m In engineering data on external files often originate in automated measurements The data has to be read by Scilab before it can be processed We ll focus our discussion on this aspect of file handling m Scilab has a set of commands for file handling beginning with the commands mopen that opens a file and mclose that closes it Between those two we use e g Check size of an object The full set of i o functions 60 in all can be found under Help Files Input Output functions Recall the related load function in Chapter 10 File handling demo 1 1 5 introduction Open write file fd path name Write data into file Close write file w Open file for reading r Define contents to read whole file Return pointer to beginning of file Define data to read Close file In this demo Scilab creates the data file that is then read later we ll se how to read from text files created by other programs Script sequences are shown to the right The script demonstrates the use of the functions mopenQ mcloseQ mfprintfQ mseekQ and mfscanf Pay attention to the following steps open as w file close w file open as r file close r file The stack pointer moves down as we write into the file and must be returned to the top before we begin to read File ha
51. get a quick overview of the discussion at hand by shifting between PPT s Normal and Slide Sorter views PPT has an advantage over PDF in allowing the reader to modify the work the way s he likes You can copy paste the provided scripts into Scilab s Editor without having to rewrite them only minor editing is needed And finally I have seen too many depressing LaTeX documents ppt documents do not require MS software LibreOffice works as well at least up to PPT 2003 but some editing may be needed Oracle threw in the towel on OpenOffice in April 2011 but it lives on in the Apache Incubator Why simulate British physicist and engineer Lord Kelvin William Thomson is known to have said When you can measure what you are speaking about and express it in numbers you know something about It Wl His words can be paraphrased in computer age terms When you can simulate what you are speaking about and present it visually you know something about it Lord Kelvin 1827 1904 Contents So ee ERTE Introduction 11 Flow control A first peek at Scilab 12 Examples Set 4 The Console amp Editor 13 Doing math on Scilab Examples Set 1 14 Examples Set 5 Matrices functions amp 15 Working with GUIs operators 16 File handling Examples Set 2 17 Animation Graphics amp plotting 18 Miscellaneous Examples Set 3 19 Examples Set 6 Converting Matlab files 20 Adieu 0 Subroutin
52. here plot2d multiple plots The previous slide showed how to create multiple graphs in a single window with two separate plot2d commands Multiple graphs can be declared in a single plot2dQ statement using a The case shown here also differs from the previous one by having argument declarations in situ Scilab does not properly adjust the plot to the window only the first legend shows plot2d style codes m We have several times come across number codes for graph colors style the number after the x and y arguments in plot2d0 Color codes are those that can be found with the getcolor command on the Console The most important ones are 1 black 2 blue 9 dark blue 3 green 13 dark green 5 red 8 white and 25 brown m On the previous slide we saw that the code 9 creates circles Plug in getmark on the Console to see the whole list including codes for mark sizes that you can use with handle commands There are in all 15 of these marks always black o 4 2 4 e ee ie x oO Alvi eo ole lt plot2d demo with matrices The simple script below demonstrates the plot2dQ command when arguments x and y are matrices and the style is 1 and 1 scfQ is used to open a new a Graphics ARNS E Window 112 7515 Otherwise the marks of the Pree ce second plot2d command would be on top of the first one i F The command is clearer if arguments
53. in Ex 3 5 Example 4 3 how to generate a cone How was the cone in the cone_creation sce previous example generated The interplay between the matrix clear clc clf vertical user defined vertical 0 1 2 2 3 3 4 Vertical reach of 3D object 1 function cone and function x y z cone reach Z Generation of a 3D object facet generation function x vertical 1 Z cos reach Extension along x axis y vertical 1 Z sin reach Extension along y axis evalddp Q are not too z vertical 1 Z ones reach Vertical z extension obvious endfunction A bare bone eval3dp script for plotting a 3D cone m Let s simplify the case to xv yv zv eval3dp cone linspace pi 1 5 pi 20 1 5 a bare minimum plot3d xv yv zv theta 60 alpha 70 Plot object el gce Get current Entity handle m And look at the result on el color_mode 24 Object exterior light grey the next slide e1 hiddencolor 30 Object interior dark grey Ex 4 3 plot Dark gray interior e1 hiddencolor 30 Box alignment defined by theta and alpha in plot3d0 Gap in the surface due to the argument linspace l pi 20 Light gray exterior e1 color_mode 24 Ex 4 3 discussion m The cone is created by the linearly increasing radius R of x and y x R cos Z y R sin Z If you change the first element in verticall from 0 to 0 5 you ll see that the tip of the cone is cut off m Ther
54. needed click OK GUI demo 2 creating pop up windows 3 5 case 5 x_choicesQ with four alternatives for three cases BB Scilab Choices Request Grade restaurant food service amp interior Pick your ame hoc Service grading Excelent _ Z Good Passable Poor _ OK and terior grading Excelent Good _Passable Poor _ 1 Scilab returns eae Ce the answer as a vector Scilab 5 1 1 returns the answer automatically with 5 3 1 amp 5 3 2 it must be asked for a bug GUI demo 2 creating pop up windows 4 5 BBB Scilab Input Value Request Compute determinant for a matrix A that is given by x_matrix Change matrix to nxn as needed The assumption is a 3x3 identity matrix Change here to 4x4 Magic Square and click OK The answer is the same as earlier in Chapter 5 It works in Scilab 5 1 1 but not in 5 3 1 and 5 3 2 GUI demo 2 creating pop up windows 5 5 Create an info list of beverage choices using listQ and messagebox Here Brandy is selected and the answer returned Same lem repeats Scilab does not return the ee re emer answer automatically in pe yg ee tee aoe Scilab 5 3 1 it did so with a simpler case but not in 5 3 2 any more GUI computer screen size amp color depth The computer screen size is needed if we want to position a GUI at a specific position in the field of view For that we need information of the computer
55. phase_i j 90 elseif clean imag i_n j lt 0 On negative Im axis phase_i j 90 else Origin imag i_n j real i_n j 0 phase_i j 0 end result j i_nG magn_i j phase_i j Matrix collects computed data Jj end Complex numbers The result is displayed with the dispQ command with everything included in the argument vector Finally the preliminary result is checked as before m And the answer on the Console In plain English i1 22 0 cos wt 129 59 A i2 24 0 cos wt 129 39 A i3 25 5 cos wt 78 79 A demo script 3 3 amp print Display summary currents il i2 13 J String matrix statement equals equals equals String matrix disp CURRENTS IN COMPLEX AND POLAR FORM Headline disp currents string result 1 statement Display result string result 1 3 2 string result 1 3 3 Check residual residual clean u Z i_n Check initial results CURRENTS IN COMPLEX AND POLAR FORM lid 14 i 17 equals 22 022716 129 47246 li2 15 2 i 18 6 equals 24 020824 129 25584 lig 25 495098 78 690068 5 i 25 equals Numeric derivation 1 3 derivative The derivative of the function f x is defined as the limit P x lim 1 foo d gt 0 d We can compute the numeric value of f x at a point x using the function derivative x x op
56. screen size It can be extracted with the argument screensize_xx There are more alternatives for the _xx suffix check Help root_properties for details Another alternative is the number of display color resolution bits It can be found with the argument screendepth These arguments are used with the function getQ meaning find out See Example 6 1 for a practical case gt get 0 screensize_px ans 1 1 1280 800 gt get 0 screensize_pt ans 0 0 960 600 gt get 0 screensize_norm ans ommo T gt get 0 screendepth ans 24 GUI demo 3 opening a predefined GW script This demo shows how to open a new Graphics Window with predefined size and position The size is defined relative to the computer s screen size in points The position in the middle of the screen has to be found by trial and error screensize_demo sce Opens a new Graphics Window with a predefined size amp location clear clc clf screen_size get 0 screensize_pt Find computer screen size size_x 3 screen_size 3 6 screensize_pt 3rd element size_y 5 screen_size 4 8 screensize_pt 4th element h_graph scf 0 Open Graphics Window h_graph figure_size size_x size_y Define GW size h_graph figure_position Position GW in the size_x 6 size_y 1 15 middle of the screen GUI demo 3 predefined GW screenshot The small GW ope
57. steps Pie size Loop size Figure handle Create before display Define pie position Plot pie color 2 Exit pixmap mode Demo 1 3 4 moving pie frozen plot Here is the blue pie in its combined start and finish position The completion of the full circle in 250 steps takes about 10 seconds with my 1 6 GHz dual core processor Demo 1 4 4 discussion m Odd things happened while I tried to get this one going The Graphics Window mostly opened as shown above but I have also seen a black ball that was before I changed it to a pie on a red background surrounded by a yellow frame topped by a red title with the animation running just as smoothly as it should m When I changed frameflag 3 to frameflag 2 the dot rotated around to the lower left hand corner and when I changed back again Scilab told that the handle is not valid any more Just go on and reload I also saw the size of the Graphics Window change from execution to execution for no obvious reason In short these events give the feeling that animation together with GUIs is not a top priority of the Scilab team Demo 2 1 2 rectangles Chancelier et al m Its to demonstrate the use of the XOR command in f pixel_ drawing_mode xor here NOR instead of XOR for reasons told below of a grey background The rectangles are drawn with xfrectQ without color code they are the
58. the abscissa t O 16 op ep enced a oe n window pawor _ part has an vaxausune Fr sase resson z se arrow in the upper right hand Tuas a 7 a 7 corner by Hepler ex can release EE mee ot e D 1p Brows ae YY it from SEZs Calling Sequence T S docking 2 analyze f y plot of a se sas y lt LineSpec gt lt Global Property gt Sand We tat tae x y lt LineSpec gt lt GlobalProperty gt aor eeioceee 6 plot Matlab function Linear 2 2 cotmpionx Plot the value of th eK To Windows Tack ar E Boonton By Wecrocoft PowerBor Scitab Console Ey New m Scab 5 2 A lt Jat Woe 957 On scripts and functions Scilab has two command types Scripts A set of commands used to automate computing Script commands are normally returned to the Console but plots are returned to the Graphics Window Functions macros Short programs that interface with the environment through input and output variables A list of common built in functions is given on the next slide Functions defined by the user can either be local integrated in a script or global stored as a separate file and accessible to any script I may use the term code to make general references to either scripts or functions a As was already said and will repeated one should rather create scripts and functions on the Text Editor SciNotes Built in functions Below is a list of common math functions in Sci
59. the plot argument 024 and its effect on the plot next slide Compute using ode which calls the previous deff function Initial current amp charge 0 Initial time 0 Time 0 0 05 8 Time as abscissa Y ode y0 t0 Time RLC Y state variable vector i q Plot current amp charge plot2d Time Y 2 5 024 Plot state vectors note transposed Y xtitle Series RLC circuit with sinusoidal input voltage Time Current amp Charge xgrid legend Charge q t Current i t Ex 5 2 ODE series RLC circuit 5 5 plot m This is the plot for the shown component values There are initial fluctuations before the situation begins to stabilize m This is the plot for more realistic component values of R 3 kQ L 0 5 uH and C 0 8 uF There used to be problems with the latter case Scilab 5 1 1 but these have obviously been solved Example 5 3 System of first order ODEs This example is modified from Povy pp 66 67 Povy also has an animation version on pp 67 68 but it causes Scilab to crash The example finishes with and interesting plot2d command The task is to plot the slope vector field for the following system of first order ODESs pea g BE AID together with a single phase portrait with the initial trajectory x O 1 and y O 1 The script can utilize either the ODE system as Povy has done or the state space repres
60. tutorials It may be confusing if you are not intimately familiar with programming Simply stated foo can be interpreted as something comes here The professional expression is placeholder name also referred to as metasyntactic variable Example for k 1 2 n foo end a Alternative placeholder names that you may come across are foobar bar and baz I prefer to use dots 3 Playing with the Console amp Editor Those awkward first steps a bit about what Scilab does Q Return to Contents Console keyboard shortcuts Keyboard shortcuts allow speedier execution of commands but require frequent use to stay memorized In the Help Browser Click Console console for a list of keyboard shortcuts The simplest ones to memorize are Open Help Browser Clear Console E Help Browser E Ui input output functions Hy L Graphics Library ay i Graphics exporting and print i GUI f Data Structures S Parameters re Boolean Gif Integers ay J Strings a di Sound file handling E d Time and Date Hy L Output functions History manager Matlab binary files 1 0 Matlab to Scilab Conversion Ti Compatibility Functions Maple Interface i Overloading Functions m 2 B22 F F console Keyboard Shortcuts in the Console Window Description ecall previous line DOWN or Ctri N jrecall next line all help clear console Jopen console box only on W
61. typed the wrong handle call gca 0 and definitely Reboot Comment multiple plots with a single command It is possible to plot multiple graphs with a als le yi 2 sin x 2 First equation command by defining the y2 2 cos 2 x 6 Second equation function arguments as plot2d x y1 y2 Plot both e qce Get Entity handle e children thickness 5 Polyline size Here is the modified plot command of the previous window demo compressed Ke plotZdix ly1 2p The result is shown here ES ee ee eee Pee aa Scilab automatically picks a ae eee ae different colors for the a a ag er aes al graphs i ists eee Window Demo w T T7177 T t 44 m Scilab warns if the Graphics Window is docked Dr EW Johnny Heikell 11 Flow control Flow control conditional branching programming bring important new structures B Q Return to Contents Introduction m We have now come to the line that separates boys from men Some examples using flow control also known as conditional branching and programming have come up in the preceding chapters but the nature of conditional branch commands like if then else has not been discussed Flow control together with subroutines are needed for serious practical simulations We shall therefore take a good look at the most important aspects of flow control Note however that loop operations are slow We
62. y axis of circular loop polygon blength 2 blength 2 blength 2 blength 2 width 2 width 2 width 2 width 2 Defines corners of polygon Set scale for isometric plot lI plot2d inf inf frameflag 3 rect 1 1 1 1 axesflag 0 h gca xtitle Waltzing polygon h background 1 Set background to black Ex 6 2 animation of a waltzing polygon 3 4 The matrix align turns the polygon into a new angle Change theta Plot rectangle as it waltzes its loop values to see some if interesting effects pie Sie theta turns t i Angle of polygon alignment a Here the handle is used align cos theta sin theta sin theta cos theta polygon to set the fill color of i Realigas polvaed Number of turns per loop the polygon the h foreground 2 Set fill color to red y fpoly align 1 is i align 2 is i i xfpoly align 1 x_axis i align 2 y_axis i e executed by Fills polygon with defined color XIPOLY h foreground 5 Change to blue for border h thickness 3 Set border thickness to 3 Next the handle defines xpoly align 1 x_axis i align 2 y_axis i lines 1 the border color in this Draws polygon border in defined color J end case the executing function is xpolyQ Ex 6 2 animation of a waltzing polygon 4 4 In this screenshot the polygon rectangle has made just over three quarters of its counterclockwise loop At the same t
63. zero for values below 1e 10 gt M testmatrix magi 4 1 450D 12 gt clean det M ans 0 Deleting rows and columns Rows and columns can be deleted by using a pair of square brackets We start with the 4x4 magic square denoted m because we shall distort it We first delete the third column The Colon Operator argument is used to retain all rows the argument 3 points to the third column The result is a 3x4 matrix m Inthe second instance we delete the _ second row to end with a 3x3 matrix sm 1032139 0 10118 gt 96 1254 15 14 1 m 1G amp f 2 13 See IOa e 9 e fab We 4 15 14 1 Changing rows and columns The logic on the previous slide can be used to changing rows and columns We start from the previous 3x3 matrix ee First change elements in the second row to zeros m Then we change the last column to ones note transpose es These operations can also be seen as inserting a defined row column vector in place of an existing row or column Addressing matrix elements by linear indexing gt M testmatrix magi 4 16 2 3 13 Sa Cis 10 8 Boe o ie 4 14 15 1 gt M 1 6 11 16 ans 16 11 6 1 Scilab regards matrices as column vectors This allows us to address matrix elements in a simplified way We start from the 4x4 magic square Then we pick out the element 2 4 wh
64. 0 second s Give time in seconds 3600 ERROR negative number Give time in seconds 7465 33 2 hour s 4 minute s 25 33 second s In the script the initial cleaning command is clear clc If clf was included it would cause the Graphics Window to pop up unnecessarily in Ex 2 3 it would have produced an extra empty window In this example we for the first time use a sanity check if time lt 0 to make certain that the user does not cause problems by wrong inputs In a case like this it is irritating that the Console does not become active after the execution command is given on the Editor You automatically begin to type in the response once the string command pops up but the cursor is still on the Editor Dr EW Johnny Heikell 7 Graphics amp plotting 2D amp 3D plots subplots amp other types of plots editing plots Q Return to Contents The Graphics Window Graphic window number 2 File Tools Edit Note The Demonstration feature has a good presentation of plotting functions but it also contains obsolete ones The toolbar allows rotation and ZOOM of a plot Select as current figure a Of real interest is Edit in the menu bar ac and the Figure properties and Axes ees properties that are shown when clicking Figure properties on Edit Axes properties m However Figure properties S Start entity picker ambiguous all options can be found ai traci
65. 1 2 k lt eps megs m Be careful with condition it can easily a lock the simulation in an endless loop 7 52 while if then else end The while end condition can be nested with an optional if then else instruction while condition_1l if condition_2 then foo else foo end foo end The function on the next slide is for a game in which the user should guess a random number that the computer draws The game finishes only with the correct guess while if then else end demo game sci The function draws a random number in the range 1 M that the user should guess Game finishes when correct number is found clear clc M 30 Upper limit of numbers number floor 1 M rand Draw a random number disp Guess a positive integer in the range disp 1 M State range of random numbers guess input You guess User s guess Start while condition Start if then else while guess number if guess gt number then disp Number is too big else disp Number is too small end End if then else guess input You guess User s next guess end End while condition disp Correct SCliaD ON Spy TEI fe a LAR nar type tne TUNCTION NaN LL ne LAnCAIA gt guess_a_number Guess an integer in the range 1 30 You guess 15 Number is too small You guess 22 Numbe
66. 11 20 hist3d list z x y 3D hist add x y vectors The list argument defines the distribution of random z values over the x y plane Histograms demo plot Old graphics syntax 1 2 demo script Scilab s graphics syntax changed with Demonstration of a method for producing version 3 1 This three plots y1 f x1 y2 f x2 y3 f x3 in the same frame Note how the frame COR ONEAN is defined j plot2dQ syntax for multiple_plots2 sce clear clc clf a case with three eta ee plots x2 linspace 0 1 31 x3 linspace 0 1 0 9 12 VAIO ODP e OA yl x1 1 x1 cos 2 pi x1 First graph y2 x2 1 x2 Second graph and ys f x3 y3 x3 1 x3 0 1 rand x3 0 5 Third as y2 with disturbance in the same frame ymin min y1 y2 y3 Select minimum to define frame bottom Note the frame ymax max y1 y2 y3 Select maximum to define frame top een dy ymax ymin 0 1 Border for min max definition and rect 0 ymin dy 1 ymax dy Frame limits start at 0 compare with the method used in plot2d x1 y1 5 011 rect First call with frame definitions plot2d x2 y2 2 000 Second call only type color 2 definition Example 1 2 plot2d x3 y3 1 000 Third call defines marks 1 xtitle THREE GRAPHS PLOTTED IN THE SAME FRAME Abscissa Ordinate Old graphics syntax Rotation surfaces The rotation surface is created by m
67. 5 2 3 17 Warning redefining function sqrt Use funcprot 0 to avoid this message Here you can see that the warning redefining function does have a meaning I have improperly used sart as a variable name but Scilab recognizes it is a built in function The answer is correct but one should rather change the variable name Check help name if you are uncertain if an intended variable name is reserved Programming pitfalls 4 4 the endless loop I have several times mentioned the risk of creating an endless endless_loop sce loop so let s look at this little eel Demonstrates an endless loop xecution ends only by crashing beast ME ji d ly b hing the program click on the Close button X on the Console When you execute the script you eas have to crash the program to stop 1 a a i p i t getdate it The easiest way is to press the a coon eaten Close button on the Console and while n 0 5 then reload Scilab i rand 0 normal enq Why does the loop not end SPAN Because we die from old age before the variable n by chance ts exactly the value 0 5 Have you forgotten bts about seeding rand functions If so go back to Ex 1 3 lotto draw Debugging 1 2 a Weare already familiar with Scilab s rudimentary embedded debugger that provides error messages on the Console a separate debugger window may come with Scilab 6 0 Another debugging tool is the pause
68. 95 0 5015342 0 4368588 0 7004486 0 3353388 0 8262233 0 4694334 Matrices are defined with square brackets while parentheses are used to cluster function arguments Basic matrix calculations gt A 123 456 B A C A B gt A 123 3456 B A C A B C 14 32 32 77 Addition Multiplication note transpose gt A 2 3 4 5 H inv A gt A 1 2 3 4 5 6 B A C A B iB 1 518D 16 S 799D IS 1 225 S ee Division note rounding errors Inverse matrix Note 2 Scilab returns D not e for the exponent 1 518D 16 the exact value is 0 but here we have a case of limited computing accuracy Durer s magic square German Renaissance artist and amateur matematician Albrecht 1 NW Durer s magic square is a popular example in linear algebra In the window of Durer s engraving the sum of any row column or diagonal yield the same result 34 We shall use the magic square to investigate some aspects of matrix operations The magic square will be denoted M to set it apart from other matrices Note that many matrix operations are defined only for square matrices sum transpose and diag The magic square is entered in sM 163213 5 10118 the Console s command line gt 967 12 415141 The statement sum M produces the sum of all elements This differs from Matlab where the same statement returns the sum
69. B Scilab Console al File Edit Preferences Control Applications 200 The script could also be Bit OBA 221818 executed from the Console na m Afterthe command prompt aaa W error 241 type File ploti sce does not exist exec plotl sce BB Scilab Console And the result is an ea _ _ 2 amp Z2O B A alea El The reason gt exec ploti sce error 24i To see where Scilab was File ploti sce does not exist looking Click File Display current directory The answer is shown in the lower window It looks in Scilab s program file which is not where I put it Ex 1 1 change boc Scilab Console m Click on the icon Change current directory Anew window pops up Define the right file with the drop down menu m Click Open You can then returmto the Console and type in th command exec plotl sce m And it works as seen on the next slide The command chdir allows the directory to be z p i Filename H Dr EW Writings Sdlab examples changed on the run a rr Ex 1 1 plot and echo Up pops the Graphics Window with a plot of the defined function while the script is echoed to the Command Window Console Graphic window number 0 File Tools Edit gy Slab Console Ene Edit Preferences Control Applications pexec picti sce rzor 241 Fiie picti sce does not exist HC Program Files sciiab 3 6
70. DRAWS 10 15 20 25 30 35 40 Lotto numbers 1 39 Ex 1 3 comments 1 3 This was not exactly an engineering problem but it showed many features of Scilab The UDF in Task 1 is unusual in being closed having no input or output arguments you just use it as it is The local UDF demonstrated in Task 2 is the normal case a In addition to randQ Task 1 brings in several useful functions getdate0 floor unique and gsort0 The script in Task 2 is commented at length Adding headings and comments takes time and they require space but comments are absolutely necessary to understand the program at a later date m Task 2 introduces the dialog box a GUI graphical user interface feature to which we shall return in Chapter 15 Ex 1 3 comments 2 3 In addition to the plot and plot2d commands that we used Scilab has numerous other ways of creating plots together with options for adding clarifying text strings to the plots Plotting will be covered in more detail in Chapter 7 m Flow control in this case the term refers to the use of conditional branch structures will be discussed in Chapter 11 Examples 1 1 1 3 were also intended to stress the fact that we are forced to think matrix wise when working with Scilab For instance Scilab immediately generates an error message if we attempt to do ordinary multiplication when a parameter is in matrix form and requires Dot multiplication Recall
71. Dr EW Johnny Heikell Scilab for Real Dummies Introducing an Open Source Alternative to Matlab v1 0 Scilab 5 3 2 5 3 3 Johnny Heikell About this presentation I compiled this presentation while familiarizing myself with Scilab for basic engineering applications The exercise taught that a reason to the limited spread of Scilab is lack of good tutorials in English which makes learning Scilab a frustrating experience for programming newbies It s a pity because Scilab deserves better recognition Hopefully this presentation can be of use to at least some Scilab aspirants The text no doubt has shortcomings and errors I hope to come up with an improved version in a not too distant future with Scilab 6 Please post comments amp suggestions at http scilabdummies wordpress com Espoo in August 2011 Copyleft This material is released under the only l condition that you do not put restrictions or a price I Yohuny Aethell tag on your redistributions modified or not and i l l add this requirement to child copies l www heikell fi Otherwise J Heikell 2011 LinkedIn Pee E Tribute to old gods The best Scilab tutorials are non English The following are the ones that I have consulted most for this work e Timo Makela s Scilab Xcos tutorials 3 parts in Finnish lt http sites google com site tjmakela home gt Heavy on mathematical formalism standard dull LaTeX typesetting but the best o
72. E However we now want to define the current i t and charge q t for a sinusoidal input signal and oe conditions i 0 0 and q 0 Kirchoff s second law gives di t 1 R 0 3Q L Ri t a t u t nO ee L 0 5H C 0 8F where u t sin 5t t q iat Of eee 0 Ex 5 2 ODE series RLC circuit 2 5 No substitutions are required in this case since q and its derivative 1 are state variables The first order equation system is therefore m Which gives the following state space expression q O 1 1 fF dt fu SS 1 s LC E L Remember x Ax Bu Ex 5 2 ODE series RLC circuit 3 5 script There is nothing new here compared to the previous RLC second order D z series __RLC_ODE sce Simulation of the current i t and charge q t in a series RCL circuit with sinusoidal input voltage and initial conditions i 0 0 q 0 0 Legend ss state space clear clc clf Define circuit components Resistance Ohm Inductance Henry C 0 8 Capacitance Farad Define state space equations amp input signal A 0 1 1 L C R L SS system matrix B 0 1 L SS input matrix deff ut u t ut sin 5 t Sinusoidal input deff ss RLC t y ss A y B u t SS expression Ex 5 2 ODE series RLC circuit 4 5 script The odeQ is the same as in the previous RLC case Check
73. Example 1 1 Ex 1 3 comments 3 3 rounding functions The rounding function floor is one of four rounding functions in Scilab round fix or int floor and ceil0 Pay attention to the difference o tpn between the first and the two last gt round 2 7 round 2 7 gt fix 2 7 fix 2 7 ones ans rounds to nearest integer fix or A at r P returns integer par ans 2 gt ceil 2 7 ceil 2 7 ans Dr EW Johnny Heikell 5 Matrices functions amp operators An overview of basic matrix operations functions and operators Q Return to Contents Introduction As Scilab is built around matrices we are forced to use them Scilab stores numbers and characters in matrices A matrix can be seen as a table consisting of 77 rows and 7 columns mxn matrices also denoted xj matrices Scalar variables do not exist per se they are treated as 1x1 matrices The general form of a Scilab matrix here 3x3 matrix is A 11 12 13 21 22 23 31 32 33 Row elements can also be separated by commas A 11 12 13 21 22 23 31 32 33 In both cases semicolons separate rows m The next page shows both alternatives for the 3x3 matrix The vector has never been of the slightest use to any creature Attributed to Lord Kelvin The 3x3 matrix Both alternatives for expressing matrices are interpreted inthe gt same way by Scilab Pick whichever you like
74. Fs Task Write a function that calculates the area of a triangle with known side lengths The function is entered on Editor It is then loaded into the Console using the Editor command Execute file with echo The function is executed by entering the function name and input parameters side lengths on the Console function A triangle_area a b c The function triangle_area calculates the area of a triangle with side lengths a b c funcprot 0 p a b c 2 p half perimeter A sqrt p p a p b p c endfunction gt function A triangle_area a b c gt The function triangle_area calculates the gt area of a triangle with side lengths a b c gt funcprot 0 gt p a b c 2 p half perimeter gt A sqrt p p a p b p c gt endfunction gt triangle_area 4 5 6 ans 9 9215674 Local and global subroutines a are embedded in a script and valid for it alone globa are saved separately and accessible to any script Result 2 Scilab script Local and global variables You will run into the terms local and global variables and they need a short clarification As with functions Scilab has two types of function variables local and global a Local variables are limited to a specific function a Global variables are available to and can be altered by all functions in which the variable has been declared global The transfer o
75. H gt exec ploti ace gt picti sce i gt A sample 2D plot of a sine function gt with the abscissa x 0 lt 19 f gt a applitede A increases with x gt The function itself i9 y x 7x 0 3719 7 The ascassa x is a row vector gt A 0 5 x3 Modulated amplitude raw vector gt y sis 3tx Elemeant by elemest qulciplicataon gt plotty Pict command Ex 1 1 comments 1 4 command details Editor contents will from now on be shown on light green background ploti sce A simple 2D plot of a sine function with the abscissa x 0 10 and amplitude A increases with x u The vector definition The function itself is y x x 0 0 1 10 can be interpreted as from 0 to 10 in steps of 0 1 x 0 1 10 The abscissa x is a row vector ASOSI Modulated amplitude row vector y A sin 2 x Element by element multiplication plot y Plot command Multiplication by the is necessary to tell Scilab it should multiply the vectors element by element Change to ordinary multiplication and you ll get this on the Console gt exec H Dr EW Writings Scilab examples plot1 sce 1 y A sin 2 x Element by element multiplication error 10 Inconsistent multiplication atline 10 of exec file called by exec H Dr EW Writings Scilab examples plot1 sce 1 Ex 1 1 comments 2
76. Hahn amp Valentine used ATOMS 1 6 installing new toolboxes m Recall the problems with ATOMS that I mention in Chapter 1 m ATOMS ap T mOdule Management for Scilab allows the user to download and install external toolboxes modules m There is reason to take a look at which modules might be of use since specialized tools can limit the time needed to solve a problem Start by hooking up the computer on the Internet and clicking on the ATOMS icon on the Console If you are unlucky you will see the following message on the Console I was unlucky and others have been as well atomsDownload The following file hasn t been downloaded URL http atoms scilab org 5 3 T OOLBOXES 32 windows gz Local location C Users Johnny AppData Local Temp SCIl_TMP_2772_ atoms 1_ TOOLBOXES gz m The bug Scilab bug 8942 remains unsolved and its true influence is unknown to me The Scilab team gives the unhelpful suggestion to download the mentioned file ATOMS 2 6 what s available This IS the ATOMS I Main categories ATOMS main window Texts lt overlap a bit but List ofnstaled modules basically it is a list seam i Aerospace Contributed Scitab of contents mi T e Data Acquisition B Data Analysis And Go ahead and try to find something of i B Datz tandiing interest even if E Education there isn t much for us engineers mams nee Another problem is ee that there iS Num
77. able from list Demo 2 Case 3 x_choices As previous but with multiple choices Demo2 Case 5 x_mdialog As previous but with multiple string parameters X_matrix Vector matrix input window Demo 2 Case 6 listQ Creates a list of objects Demo 2 Case 5 Matlab s struct is also available in Scilab x_dialog Window with multi line dialog Demo 2 Case 4 GUIs messagebox The syntax of the messagebox function is the following 22 66s messer message tithe Tih mni en modal gt Message a you want to convey ixn vector j strings with button legends Box title the default is Scilab modal tells Scilab to Message Icon to be placed wait for user actions in the box otherwise 0 is returned Definable icons are error hourglass mM O info passwd question and warning GUI demo 2 creating pop up windows 1 5 Default title Recall that this pop up window was created by adding the command messagebox The result of the EB Scilab Message double integral is string 1 at the end of the script of Example 5 4 Case 2 is The Yes No buttons have no meaning since the case is not declared modal and Scilab by design returns the default zero 0 GUI demo 2 creating pop up windows 2 5 x_choose with four alternatives x_dialog with input transformed from string to matrix Change matrix as
78. above 1 Default variance 1 Count signal gt mean var elseif signal 1 j lt ave 1 Default variance 1 below below 1 Count signal lt mean var else If within variance limits within within 1 mean var lt signal lt mean var end end for If else end demo script 3 3 Display on the Console Total mean and variance limits This particular form of multiple plots was discussed earlier and is worth keeping in mind Display result disp Result from generating string n Gaussian distributed samples disp signals with mean string ave and variance 1 disp string within samples were inside variance limits disp string above above upper variance limit and disp string below below lower limit Plot result Array for x axis y1 ave ones 1 n Array for mean value y2 ave 1 ones 1 n Array for upper variance limit y3 ave 1 ones 1 n Array for lower variance limit rect 0 ave 4 n 1 ave 4 Set pot window plot2d x signal 2 011 rect Plot samples plot2d x y1 5 000 Plot mean value plot2d x y2 3 000 Plot upper variance limit plot2d x y3 3 000 Plot upper variance limit legend signal average variance xtitle GAUSSIAN RANDOM SAMPLES Sample Sample value for If else end demo print amp plot 69 6 of the samples a
79. ar plot d 0 45 0 55 plot2d theta AF_norm1i AF_norm2 style 2 5 tor ic m leg d 0 55 d 0 45 The array factor See xtitle ANTENNA ARRAY FACTOR N 10 Beam angle 60 deg plotted both in linear and Theta radians Normalized amplitude polar presentation subplot 212 Polar diagram d 0 55 polarplot theta AF_norm2 style 5 xtitle POLAR DIAGRAM FOR d 0 55 Ex 3 4 plot Grating lobe Main lobe ANTENNA ARRAY FACTOR N 10 Beam angle 60 deg The plot verifies the common according to which the array element spacing must satisfy the condition or A Q detrimental grating i PANN lobes will show up Theta radian POLAR DIAGRAM FOR d 0 55 Note that there is a T a l in the 3 pa Main lobe other half space only the 90 case has been plotted ye Grating lobe 90807 Ex 3 4 modified plot m This case shows d 0 45 only Other changes are Element spacing d 0 75 Element number N 30 Scan angle 30 Scilab 5 1 1 tended under conditions like these to present only a part of the polar plot but at the same time increase the size and let the polar plot overflowed the linear plot which wasn t bad This seems to have changed ANTENNA ARRAY FACTOR N 30 Beam angle 30 deg d 0 75 0 5 0 0 0 5 1 0 Theta radians POLAR REPRESENTATION 90807 git Sto 20 3 Main lobe Se a0 0080700 Example 3
80. are collected in the columns vector inside the for end 010 8 The result is plotted as step functions function out lottodraw in dt getdate Pick current date rand seed 1000 dt 9 dt 10 Initialize random generator out floor 1 39 rand 1 in Draw Lotto row out variable while length unique out lt in If number repeats in row out floor 1 39 rand 1 in then a new row is drawn end endfunction MAIN Call subroutine update histogram plot M evstr x_dialog Enter of Open dialog box lotto draws N 7 Lotto numbers to draw columns zeros 1 39 Initiate collecting vector for k 1 M numbers lottodraw N Call to subroutine columns numbers columns numbers 1 Add 1 for drawn number end x linspace 1 39 39 Define x axis plot2d2 x columns style 2 Plot as step functions xtitle RESULT OF LOTTO DRAWS Add title amp labels xlabel Lotto numbers 1 39 ylabel Hits Ex 1 3 task 2 execution amp plot E Scilab Input Value Request 3 Enter of lotto draws ox cancel The result is plotted on the Graphics Window It is not too bad considering that the average of 10 000 draws is 7x10 000 39 1 795 It takes my 1 6 GHz dual core processor about 10 seconds to compute 10 000 draws The dialog box pops up when executing the script Enter the wanted number of Lotto draws and Click OK RESULT OF LOTTO
81. ariables from the previous example are displayed BB Scilab Console File Edit Preferences Control Applications i 26X 0 O b Aa a 2 e0 gt who our variables are subdemolist resize gui help fodules_ managerlib parameterslib fft spreadsheetlib texmacslib compatibility functilib stringlib Sz optimsimplexlib ainterpolationlib iolib beta linspace tc_ac demo _gui_update WSCI atomsquilib Simulated _annealinglib scicos autolib demo _toolislib tclscilib Statisticslib special functionslib s optimbaselib linear _algebralib integerlib alpha h delete delete_frame create_frame home atomslib genetic algorithmslib scicos_utilslib development _toolslib m2scilib windows _toolslib sparselib polynomialsiib neldermeadilib jvmlib dynamic linklib fmtuser data gcft get_figure handle update button_position demo gui scinoteslib matiolib umfpacklib xcoslib soundlib maple2scilablib timelib Signal processinglib overloadinglib optimizationlib output_streamlib uitreelib List of variables 2 2 The command browsevar opens the Variable Browser window it used to be called Browser Variables thus the command browsevar The list that pops up gives information about the type and size of each variable Recall that the Variable Browser also can be called via the menu bar Applications Variable Browser wl T F Alan E Variable Brows
82. arnings The next slide shows what they mean Well let s see how Scilab reacts by executing the script plot fi Gfi fi Gfs mtlb_grid set gca data_bounds matrix 0 25 0 25 0 8 1 2 1 ylabel Amplitude xlabel Angle radians title Monopulse Antenna Patterns text 0 04 0 8 Sum Pattern text 0 22 0 6 Difference Pattern M to S translator plot Monopulse Antenna Patterns Yeees it comes labels and all But the which means that Scilab cannot cope with Matlab s textQ function a D a E x 0 05 0 00 Angle radians M to S translator comments Based on this example one could say that the embedded Matlab to Scilab translator is adequate A legend has to be added manually to compensate for the missing textQ information The example demonstrates partly good programming practice by declaring each logical entity However informative explanations could be added Another improvement is to use expressive variable names Why not talk about sampl_freq instead of fs and what does wxna stand for m Help sheds no light over the meaning of the second sci files that the conversion produces A paper by Sharma amp Gobbert 2010 reports that the translator cannot cope with Matlab s xlim function In their case the plot function had to be manually changed to plot2d to correct the problem Manual conversion 1 6 Case 1 script
83. arting point Let s start by plotting a sine and cosine curve on the same frame The resulting plot is not very sexy So let s do some editing to give it a more attractive appearance m Start by clicking Edit Axes properties Plot editing demo edited plot m To change sine and cosine colors Click Figure SiGe WE EEE object Colormap mark a 7N mg one 1 for 1 RED 2 BLUE Bi m Sine cosine style Axes Compound Polyline select Line solid 3 for both m x y axes Axes Text x y axis File mode on Fore color 13 Font size 3 Axis location middle Grid color 13 m Title Text SINE AND COSINE Font size 3 m Style Font size 2 Axes labels Font Color 13 Editing the Graphics Window The Figure Editor allows us to give the Graphics Editor a more colorful appearance Play for a while with the Editor s object properties and you can find e g the following alternatives Graphics Window commands The command for creating a Windows related clear new Graphics Window for delete commands are e g plots is GIE sef xdel for figures delete show window obsolete are and the obsolete ee g xselect xset xbasc Removed Single plots can be created Scilab commands starting with without the scf command x are usually associated with Graphics Window The history Obsolete functions can be seen of the x goes back to the X in m
84. at we are looking for 2 5 2 25 1 residual Ex 2 2 comments The example shows that we have to find the right method to be able to use matrix operations Is there reason to use matrices which are the alternatives a The first alternative would be to faba from the initial diagram and ap ly Kirchhoff s voltage law and solve the problem manually It is a quite tedious task a Another alternative is to start manual calculations from the set of mesh current equations by using Cramer s rule However it also requires a good dose of algebra since we have to compute determinants for several equations before we can divide the results to find the solutions In short using Scilab to manipulate matrices simplifies the undertaking With more complicated circuits the difference is even more pronounced Example 2 3 continuous time state space model The figure shows a typical a where continuous time state space A system matrix model defined by the matrix B input matrix equations C output matrix E AN D feedforward matrix y Cx Du x State vector x dx dt u input vector y output vector Ex 2 3 the task m Assume a system given by a E B E a 0 1 me ue D 0 a The input u is constant at 0 5 a The initial state vector xO O O i e x Oatt 0 The task is to plot the output y and state variable responses x x fort 0 30 Ex 2 3 script First the state Space mode
85. ations Matlab to we Scilab translator Matlab to Scilab translator What happens next you can se Module manager ATOMS on the following slide Variable Browser Command History M to S translator the process sree The conversion tool opens File _ B 1 Click File name Browse Conversion mode and identify the file that you Convert a single file Convert a whole directory want to translate Soe 2 Click Directory name Browse to point out where to put the translated script and SANN E associated products Only double values used 3 Click Convert Directory name C AUsersUohnny Documents Dr EWWriting Browse Verbose mode a Generate pretty printed code Yes The conversion produces two text documents and two SCi scripts M to S translator messages on the Console BB Scilab Console File Edit Preferences Control Applications 2 2B 8 0O B Aa a amp Scilab presents a list of translation conditions and ene also Wa rnings of loading initial environment wxexeee Beginning of mfile2sci session possible errors File to convert C Users Johnny Documents Literature Maths amp S amp T computing Matlab Schleher Result file path C Users Johnny Documents Dr EW Writings on the Console Recursive mode OFF Only double values used in M file NO The warnings Verbose mode 3 Generate formated code NO are repeated as M file reading M file
86. ative rect 5 3 5 11 fplot2d x f 5 011 rect Plot function fplot2d x g 2 000 Plot derivative xgrid Add grid to plot xtitle f x sin x x 0 1 42 0 1 AND ITS DERIVATIVE legend Function f x Derivative of f x a qca a children children 2 thickness 2 a children children 3 thickness 2 x thickness x thickness Numeric derivation 3 3 plot fi sin aitt 0 177 2 0 1 AND ITS DERIVATIVE A lesson from doing this exercise is that two deff Q functions in tandem i e one for f x followed by one for f x that utilizes f x does not work On the contrary the attempt may cause Scilab to to the legend command in the script It comes before the related handle statements but Scilab does not complain Beats me Numeric integration 1 6 definite integral Consider the definite integral gt deff y f x y 6 x2 b aN 00 dx Fea intg 2 1 if fal To solve the integral first define ONETAN the function y f x e g using W the deff function i intg pi 4 3 pi 4 f The integral can then be evaluated using Scilab s intgQ function i e A intg a b f 1 4142136 A 2 pi and gt Az intg 0 2 pi f is what you get error 24 The function integrate can be more useful in some cases Check with Help Convergence problem Numeric integration 2 6 length of an arc The leng
87. b answers on the Console So it is as a subroutine I called it window_demo scg a Not sce sci It s g for graphic Then we need a main script that uses global subroutine Note that I call the Entity handle e gce It simplifies compared to the path needed if calling the Axes handle as was done in Chapter 7 reuse_function sce Reusing graphics function vA J defenitions with handle commands clear clc SUBROUTINE load function o load window_demo scg MAIN define and plot x 4 0 01 4 yl 2 sin x 2 Horizontal extension First equation plot2d x y1 style 2 First plot blue e qce Get Entity handle e children thickness 5 Polyline size y2 2 cos 2 x 6 Second equation plot2d x y2 style 3 Second plot green e qce Get Entity handle e children thickness 5 Polyline size Global subroutines window demo 4 4 plot m Do you have problems Window Demo with the plot 10 m If yes make sure that ae sae 2 you defined the ie i window correctly E r e For instance if you do ae a aa ee GN Peo not correctly fill both he i ce a i sides in the Edit Axes MLN E ie a De ee eee Ticks list there will be ee ee TER ae ee some funny grid a ee E AT P O _ locations a a oe oe 1 m Make also sure that the OS T ee ee ee eee data bounds 5 5 a o R E a 10 10 are defined in the Axes Editor Axes Options window I
88. ce 1 6 60 Frequency range logarithmic G 1 1 i 2 pi freq R C Transfer function G_dB 20 log10 abs G Logarithmic scale phase atan imag G real G opi 180 Phase subplot 211 Amplitude plot plot2d freq G_dB logflag In style 5 xgrid 2 Blue grid xtitle Amplitude Frequency Hz Gain dB subplot 212 Phase plot plot2d freq phase logflag In style 2 xgrid 3 Green grid xtitle Phase Frequency Hz Phase deg Ex 3 3 plot i Note that the x axis label is missing for the phase plot although it was specified Scilab does not repeat it since it is the Amplitude TUTTERECO eT eT eee l 1 II same as the top requency Ha one Change the Oy etccanpccce rrariarsrrrenre ade LeU ota San oto PC I perenne I its CL I O D o e subplot declarations to 121 and 122 and the x axis label is given for both parts Example 3 4 linear antenna array The task is to investigate the behavior of the Array Factor AF also know as field intensity pattern of a linear antenna array with N 10 Radiating a A3 o N A isotropic radiating elements Baa E d when the main beam is a j p ET scanned at 6 60 and ia te Kae element spacing d 0 45 Phase Aw and 0 55 wavelengths 2 g as i gi y y For a discussion on antenna n sin NT sin 6 arrays see Brookner E ed Practical Phased Array Antenna Systems
89. ce Builder g Scilab Console File Edit Preferences Control Applications ZIX COIDA SISS S O scilab 5 3 1 Consortium Scilab DIGITEO Copyright c 1989 2011 INRIA Copyright c 1989 2007 ENPC Startup execution loading initial environment Start plotlib toolbox 0 42 Load macros Load help WsTART GUI Builder i Load macros Load help Type guibuilder to start the GUI ATOMS 5 6 Check with Badan quiver3 matlab_quiver3 sce Test Matlab s quiver3 function clear clc clf X Y meshgrid 2 0 2 2 1 0 2 1 Z cos X Y surf X Y Z hold on U V W surfnorm X Y Z quiver3 X Y Z U V W r Legend Surface normals colormap gray hold off I tested Matlab s quiver3 function with Me script in Help but The plot is wrong and Scilab yells about hold atline 10 of exec file called by on which it should know by now Pn ere aka Undefined variable hold ATOMS 6 6 discussion of problems m My troubles began in earnest with the execution of Matlab s quiver3 function No matter what I did all Scilab scripts turned out garbage plots The situation was confused by simultaneous events Apart from toolboxes I had also installed Scilab 5 3 2 had some Windows updates arriving and saw hiccups with both MS Word and Windows There was no problem with Scilab 5 1 1 Windows had been running for three years so I decided to reinstall it Only after this pro
90. cess I suspected ATOMS To cut the story short the problems were due to the Plotlib toolbox I uninstalled it and Scilab 5 3 2 worked normally again m Lessons learned Install only one toolbox at a time and test it and Scilab immediately Uninstall the toolbox in case problems emerge Building a script library Over time we accumulate a huge number of programs How should we administer them how can we later find what we need m This presentation demonstrates alternative ways of commenting scripts a most important subject when a program has to be modified in the future m Pay attention to program names Descriptive names help to identify individual programs among other programs in a large file Build your library of Scilab scripts in a logical manner In this work I have partly saved scripts on a thumb stick drive in the file H Dr EW Writings Scilab examples under the assumption that this presentation points to where to find a particular script This is not a the way to do it continuously so give your own documentation system a thought including the backup solution One option is to maintain a spreadsheet catalogue of programs with information on what a specific script does where it is located which functions it contains etc An advanced solution is documentation software of the type used in requirements management Johnny Heikell
91. cjd RS ie This example is adapted from Kubitzki inf hrung in Scilab pp 41 42 and can be compared with the earlier one for plotting a 3D sinc function The script introduces the use of colormaps to identify graphics colors The argument of coppercolormaps defines the number of colors in the map 32 is typical Note that color_map works on the Figure level f gcfQ Here we use the pair drawlaterO and drawnow0 to control the plot process A sinc colormap sCe Define and plot 3D sic funtion graphic adjust properties with handles clear clc clf x linspace 10 10 50 Linear space of x y x Ditto for y Uf SUBROUTINE sincf function z sincf x y r sqrt x 42 y 42 eps Auxiliary computation z sin r r Amplitude endfunction MAIN Compute sinc function n w feval x y sincf Evaluate with SUBROUTINE sincf Plotting amp plot control A drawlater plot3d x y w Suppress plotting until ready Suppressed plot function ea f gcf Get Figure handle a ee coppercolormap 32 Set color table h gca Get Axes handles h rotation_angles 87 42 Set angle of observation h children color_flag 1 Use current color table xtitle sinc X Y Z Title amp legend drawnow Plot now Ex 3 5 3D sinc plots amp comments Scilab has numerous colormap alternatives that allow the color of a 3D plot to
92. clc clf Initialize drawing process Get current Axes a data_bounds 0 0 100 100 Boundaries for x amp y coordinates xtitle Click left mouse button amp drag to create a rectangle Click a second time to freeze Display instruction show_window Put Graphics Window on top Start drawing rectangle in the Graphics Window button x_coord y_coord xclick Point of mouse button click xrect x_coord y_coord 0 0 Start rectangle at mouse pointer x amp y coordinates rectangle gce Get rectangle handle mouse x_coord y_coord 1 Mouse pointer 1x3 matrix Interacting with the GW 68 4 script 2 2 The loop starts by checking the status Execute mouse commands for rectangle of the mouse Recall while mouse 3 1 do Repeat until second click mouse xgetmouse Check mouse position from the pi x_coord1 mouse 1 Mouse location in x plane slide the vector y_coord1 mouse 2 Mouse location in y plane mouse x coord x_origin min x_coord x_coord1 Define x origin d 1 i y_origin max y_coord y_coord1 Define y origin y_coord width abs x_coord x_coord1 Define width of rectangle height abs y_coord y_coord1 Define height of rectangle Following that new rectangle data x_origin y_origin width height data are calculated Change rectangle origin width and height for the rectangle The finishing touch is to define ne
93. code into logical entities with the help of subroutines Separate structural entities by empty rows and headline comments Indent rows loops print commands etc for increased clarity Be liberal with the use of comments keep space between the command and its row comment Simple is beautiful a good program is short and unambiguous For a more thorough discussion see textbooks on software engineering Programming pitfalls 1 4 Computer programs cannot be tested to guarantee 100 reliability There is the danger of both hidden and in retrospect obvious bugs Avoiding common programming pitfalls should be a minimum goal and requires that we are familiar with them Basic Scilab tutorials do not pay much attention to programming pitfalls Eine Einf hrung in Scilab by Bruno Pin on original in French for me German is far easier is an exception Its last chapter briefly discusses programming pitfalls Worth taking a look at A search on the web for Matlab pitfalls provides some hints There is also a useful discussion in Chapter 9 of Hahn Valentine Essentia Matlab for Engineers and Scientists 3rd ed Butterworth Heine mann 2007 The term bug according to anecdote was coined in 1947 when Grace Hopper Grandma Cobol of the US Navy identified a computer problem being caused by a moth in a relay tube connector the story varies The original bug was thus a hardware related prob
94. color 5 red border h foreground 5 But frankly it can be a pain and you want to throw the computer out the window If so check if the gca handle has any children at all Flawed error messages m Scilab s debugger shows strengths and flaws in the error messages that invariably pop up before one s plot commands are right m Here are two error messages that I have got eee isa a gt The real problem was first and second arguments have incompatible dimensions that I had not used at line 16 of exec file called by the Dot Operator in exec H Dr EW Writings Scilab examples derviative_2 sce the equation for y1 while executing a callback Bogus warning Scilab crashed l error 13 and had to be reloaded to Redefining permanent variable E i i roA e a xe iam Balls while executing a callback Jefo rs ee i a cle More info on plotting E Help Browser In the Help Browser Click Graphics Library and under it you find info on e g 2D plots 3D plots axes_operations iE axeS_properties 0 oad there Ke peat Aoao da cons nee nine aes etc ia drawing as well as the parameters default values for the children creation axes_operations axes_operations Scilab manual gt gt Graphics Library gt axes_operations gt axes_properties axes_properties 8 8 8 S 8 e description of the axes entity properties Description Axes properties 1 parent N OW at ea st IS
95. ctions This example demonstrates the bode and gainplotO functions when operating on the earlier Gaini and Gain2 expressions bode plots also the phe Ex 3 1 comments The script was modified after being copied from the Scilab Group User s Manual and pasted into Editor When copy pasting Editor tends to interpret citation marks c s etc wrongly and they have to be corrected manually Scilab is strict with the arguments for polynomial expressions If for instance the c is left out from the expression poly 0 0 2000 200 25 1 s c it will be translated into 10000000s2 10455000s 455225s 2226s s Be careful m There is an advantage in using self documenting expressions here exemplified by naming the polynomials Gain1 Gain2 etc The separate Bode plot demo showed that the bode function has an advantage in providing also the phase of the system of interest The difference between Black s diagram and Nichols chart will be demonstrated in Example 3 2 Example 3 2 Black vs Nichols This example adapted from Povy s tutorial p 78 shows what the chartQ command adds to Black s diagram The first vector argument of chart defines the iso gain curves to be plotted The second argument defines iso phase curves list defines plotting properties the last argument does not have any effect Check with Help for details black_nichols sce Demo
96. der here columns first 2 Matrices with string elements strings were used in the dialog box in Ex 1 3 and will be gt size You Me Alpha Beta Two Three discussed in detail later are da treated the same way 3 2 length m The function lengthQ is related to size For a matrix with numeric elements length returns the number of elements m For a matrix with string elements length returns the number of characters in each gt element Note that matrices with mixed numeric and string elements are not allowed gt length 1 23 456 7890 9 ans 3 gt length Hello world SCILAB Alpha Beta ans mi 6 4 find condition The function find identifies and returns the row locations of those matrix elements that satisfy the Boolean condition stated in the argument An empty matrix is returned in case no element satisfies the given condition The statement X 3 is not a valid Boolean condition Although a numeric answer is returned it is not legitimate Later we shall se that find can also be used with strings gt X 9 1 8 273 635 gt find X lt 5 ans 2 4 6 8 gt find X 8 ans gt find X 8 ans gsort m Scilab does not recognize Matlab s gt matr 1 4 2 2 10 3 3 450 5 sortQ function it used to before matr version 5 3 Instead we must use gsort which is
97. e There is a cost involved in shifting to a new software tool even if the tool is gratis e Training and documentation support is poor e There are no interfaces for other software tools that we use e It seems to be rather slow Conclusion Scilab like other open source programs lacks credibility in the eyes of users particularly professional users The situation is similar with various excellent Linux distros and the LibreOffice office package Users trust products that have to be paid for Scilab advantages Numeric computing is better suited for complex tasks than symbolic computing Not all mathematical problems have closed form solutions numeric computing will therefore always be needed Scilab is similar to Matlab and keeps developing even closer It is quite easy to step from one to the other Scilab requires less disk space than Matlab and GNU Octave It includes a Matilab to Scilab translator m files to sci files Data plotting is said to be simpler than with GNU Octave but the trend is toward more complex handle structures The Xcos toolbox installs automatically with Scilab be it that Xcos is not compatible with Simulink Scilab installs without immediate problems on Windows computers Scilab is free if your wasted time and frustrations are worth nothing The fight for a limited number of expensive licenses Matlab Mathematica etc is not an issue in professional life Scilab
98. e 5 reflects the fact that it is my fifth attempt to get it right Let s see if Scilab can read the csv file There are two command options M fscanfMat for a matrix of real numbers text data is ignored M text fscanfMat for a string matrix The output for both alternatives are shown on the next slide For Help press Fl After that we can write a script to plot the data Spreadsheet data 3 7 csv file read by Scilab gt M fscanfMat l file_spreadsheet_demo5 csv G text S fscanfMat M gt G text fscanfMat l file_spreadsheet_demo5 csv text Reading Outdoor Indoor Q Note If you work with MS Excel you use of course the ending txt instead of csv CSV stands for Comma Separated Variable SA ee lee M fscanfMat Se E Spreadsheet data 4 7 script for plotting 1 2 The fscanfMatQ command cannot be split on two rows even if it is not needed in this case The size name r function is used to determine the number of matrix rows Matrix columns form separate vectors spreadsheet_data_plot sce The script reads data from the test file file_spreadsheet_demo5 csv determines its ength and plots its two measurement sets clear clc clf Open the file determine number of rows and form vectors of its columns data_file fscanfMat IH file_spreadsheet_demo5 csv
99. e Atoms Xcos and Demonstrations icons came with Scilab 5 2 Launch Editor Opens Scilab s Editor SciNotes another part of its Integrated Development Environment IDE Basic tutorials seldom stress the fact that normally we work with write edit save run executable Scilab scripts on the Editor not on the Console The Editor is presented a few slides below File Edit Preferences Control Applications Change Current Directory It can also be found under File in the menu bar You need it to point out from which directory folder Scilab should search for a script that you want to execute run The Help Browser 1 3 In the Console Click on the Help Browser icon to open it Help discussions become more readable if you print them as PDF files The Help Browser is a brief encyclopedia of Scilab s main features and functions Explanations of functions are augmented by see next slide for a demo but this does not compensate for a good tutorial E Help Browser gt 88 Trigonometry Elementary Functions Scilab manual gt gt Elementary Functions gt abs abs absolute value magnitude Calling Sequence t abs x Arguments X real or complex vector or matrix real vector or matrix Description abs x is the absolute value of the elements of x When xis complex abs x is the complex modulus magnitude of the elements of x Examples Trigonometry Elementary Functions
100. e and black To which I got this answer You can modify more easily the colors configuration in modifying the file C Documents and Settings Johnny Application Data Scilab scilab 5 3 scinotesConfiguration xml or a path which is similar I found scinotesConfiguration xml under C Program Files scilab 5 3 modules scinotes etc XML color codes must be changed in this file I wish you good luck Editor menu bar 5 5 Execute Untitled 1 SciNotes Lene Edit Search Preferences Windo Execute The Execute drop down window contains three options a file with no echo Ctrl Shift E file with no echo A file with echo Ctrl L simple execute command until the caret with echo Ctrl E same as clicking the Execute icon on the toolbar file with echo Executes the script and echoes it shows it on the Console The Execute commands used to be simpler I have no idea why they changed them this a Until the caret with way My recommendation is echo Beats me what it means to use the Execute icon on the toolbar see next slide Editor toolbar New Opens a second Untitled 1 SciNotes p M tab for a new script to File Edit Search Preferences Window Execute be edited the same command can be found under File T oo Pz ees ee a ome Sy ee a O Bb hH ala So es a er a Untied 1 109 The Save icon looks like the Dutch tricolor but you ll get used
101. e are six elements in the vector verticall The last one 4 is never used since the third argument in eval3dpQ is 1 5 meaning that only the first five vector elements are needed Hence the z axis of the plot is 0 3 a I left a gap in the perimeter of the cone to demonstrate the role of the second argument in eval3dp Q m This example has correct shading of the object The surface pattern in Ex 4 2 is no artistic creation but messed up due to overlapping Z values Ex 4 3 how to transform the cone to a vase How do we create the vase that Chancilier et al talk about Quite obviously we have to alter R in X R cos Z y R sin Z Here is one way to do it by introducing a vector R_factor that compensates for the linear increase in R And the result is shown on the next slide vase_creation sce A bare bone eval3dp script for plotting a 3D vase clear clc clf Vertical reach of 3D object Correction matrix function x y z SCHEMES Z Generation of a 3D object Radius of vase R f Z x R 1 Z cos reach Extension along x axis y R 1 Z sin reach Extension along y axis z vertical 1 Z ones reach Vertical z extension endfunction xv yv zv eval3dp cone linspace Y opi pi 20 1 5 plot3d xv yv zv theta 60 alpha 70 Plot object el gce Get Current Entity handle el color_mode 24 Object exterior light grey e1 hiddencolor 30 Object interior dark grey
102. e xpoly function draws a polyline the polyline is a closed X ae eee Ht hexagon i y cos 2 pi 0 5 6 polygon if the numeric argument _ xpoly x y lines 1 a of xpoly is gt 0 e qca Get Axes handle Note the e parent definition eae e A VA F ENA 5 color grey set backgroun that refers one step up in the e box on Switch frame on hierarchy to Figure e foreground 5 Red frame color e data_bounds 2 2 2 2 Frame size a With e children we move one e children foreground 2 Blue graph color step down in the hierarchy Polylines 2 3 xpoly plot amp discussion And this is the polygon that we have created The unedited hexagon can also be drawn with the following script It is left open if we do a small change to the x y arguments Polylines 3 3 xpoly lessons learned m Scilab showed unexpected behavior with this script The background color could turn black with the command e gce e parent background 34 The gcf handle revealed that the setting was background 2 and the handle command had no effect The definition color grey feels more stabile than its numeric counterpart The Graphics Window did not always change when the script was changed and executed The background stayed grey even if e parent background color grey was deleted When shifting between two scripts on the Editor the background color was exported to t
103. ed Display To output a listing of text information on the computer screen Echo To display commands or other input typed by the user Execute To run a program or carry out the instructions specified in a command m Print To output information on a computer printer often confused with display m Returns Results provided by the computer in response to a command On handles You will often see Scilab s Help Browser refer to a handle but Help does not provide a helpful explanation of the term Here is a brief account In graphics software the word handle refers to the points placed around a figure or plot that allow you to manipulate the object see figure A Matlab tutorial gives the following explanation that is also valid for Scilab Whenever Matlab creates a graphics object it assigns an identifier called handle to it You can use this handle to access the object s properties You need handles to edit graphical plots beyond the means offered by basic plot functions plot2dQ plot3dQ etc a We ll return handles when discussing graphics amp plotting Ch 7 Check handles with gcf m The function plot2dQ produces the plot below The command gcf gives the list to the right The list is the handle for the defined function Scilab literature also refers to individual rows in the list by the term handle cele a The term foo is used in many
104. ed from rectangular to polar values by computing their magnitude and phase The clean function is used to eliminate computing errors around zero clear clc Compute complex currents Z 80 12 i 80 12 i 80 100 20 12 i 20 20 8 i Impedance matrix u 100 i 500 0 Voltage matrix i_n Z u Compute i Z u Calculate magnitude and phase Define empty current matrix phase_i Define empty phase matrix for j 1 1 3 Compute for three currents magn_i j sqrt real i_n j 2 imag i_n j 2 Computes magnitude Complex numbers demo script 2 3 This is where one has to be careful and consider all alternatives Note that the zero 0 condition gets a margin for computing errors through the clean function Each time the for end loop is run through the matrix resultQ collects the data Calculate phase f if clean real i_n j gt 0 then In 1st or 4th quadrant phase_i j atan imag i_n j real i_n j 180 pi elseif clean real i_n j lt 0 In 2nd or 3rd quadrant if clean imag i_n j gt O0 then In 2nd quadrant phase_i j atan imag i_n j real i_n j 180 pi 180 elseif clean imag i_n j lt O then In 3rd quadrant phase_i j atan imag i_n j real i_n j 180 pi 180 else On negative Re axis phase_i j 180 end elseif clean imag i_n j gt 0 On positive Im axis
105. elp for advanced print features DECAYING LINEAR CHIRP IN SCILAB f modulation2 sce if Plots a sinusoidal function of the type ji s At sin wt x t phi where w angular velocity x t frequency modulation phi phase shift and A t amplitude H ear clc clf f Frequency f i4 Initial phase shift 4 iw End of plot inspace O fin 1 000 exp t an n ii A gt 33 ll vel uss wt O tA2 phi SINUSOIDAL PLOT ait ylabel Amplitude SINUSOIDAL PLOT i 1 i i i 1 1 i oo 02 04 06 08 10 12 14 16 1 8 d t Ex 1 2 checking To show that the frequency is linearly modulated we can add frequency as a function of t to the plot For that we add the function f_mom to the script The plot command must also be modified We shift back to the plot command and include both parameters together with color information Cr b fuse x label t as an argument of xtitle swap y label for legend the argument 2 refers to the upper left hand corner f modulation3 sce Plots a sinusoidal function of the type s A t sin wt x t phi where w angular velocity x t frequency modulation phi phase shift and A t amplitude Second plot for momentary frequency values clear clc clf jp e Frequency w 2 pi f phi pi 4 Initial phase shift fin 4 pi w
106. end disp k string k Ik 200660 time 10 142 disp time string toc tic k length find rand 1000000 1 lt 0 2 disp k string k disp time string toc Ik 199649 time 0 298 Discrepancy in time measurements 1 2 I wanted to check Scilab s computation time for a cased given in a textbook on Matlab by Hahn amp Valentine First I did it on the Console and then on the Editor but the results did not match The result is 97 531 seconds on the scilab matlab_loop sce iG Console Clearly not Je true because the tic gt for n 1 100000 s 0 gt S S N an can for n 1 100000 gt end without delay s s n end cunt tee It is only 0 453 s i a isp time gt disp time when done on the Editor That s more d 97 531 like it Let s try with vectorized functions next slide Discrepancy in time measurements 2 2 And here is the same in vectorized form Now the Console tells of a threefold scilab matlab_vectorized sce gt tic Improvement in clc gt n 1 100000 computation time T errr TEE but still not true S SUM time toc gt time toc and the Editor Mey ae paced agrees about the improvement but oe 32 994 the discrepancy anre Conclusion There is a bug either in my approach or in Scilab but Scilab seems to execute faster than Matlab on the old Pentium II processor that
107. entation We ll select the latter in line with earlier examples Ex 5 3 script The state space function is named firstorder0 The vector field is drawn with fchamp ode has only one argument and accepts only one name for the initial condition gt x and y are renamed x 1 and x 2 respectively as shown in the arguments for plot2dQ ode_phase_plane_m sce The scripts plot the phase plane of the equation system x y y x y together with a single phase portrait that satisfies the initial condition x 0 1 y 0 1 clear clc clf funcprot 0 First order transformation A 0 1 1 1 State vector deff ss firstorder t x ss A x Create amp draw slope vector field z linspace 1 5 1 5 10 fchamp firstorder 0 z z Draw vector field Create phase portrait Initial condition t linspace 0 30 300 x ode x0 0 t firstorder x state variable vector with x x 1 y x 2 Plot phase portrait on slope field plot2d x 1 x 2 5 004 xtitle Phase plane of dx dt y dy dt x y Ex 5 3 plot Full plot Phase plane of dx dt y dy dt x y n w 1 S Phase portrait 7 NAA with initial 1 0 YY condition 1 1 4 Zoomed center area Scilab does not put the haircross at the origin which is just as well Example 5 4 Simpson s rule the task m This example demonstrates integrat
108. ents this as the drunk Sailor problem It demonstrates a random Creates a track of marks that proceed randomly in the x y plane The walk starts at the origin walk one fixed step at a time and proceeds for a predetermined number of steps randomwalk sce u The whole process is either up down right or left performed in a single function randwalk steps clear clc clf that has to be executed from funcprot 0 the Console f function randwalk steps In this case there is no x zeros 1 steps 1 Counter for x track problem with having the y zeros 1 steps 1 Counter for y track el for k 1 steps random generator inside the direction floor 4 rand Draw random move for end loop select direction The script pl mark Bee en l lo for each sera T KKEDEXOH Move ight Po Y K L Y K they cannot be distinguished case 1 then on the plot on the next side x k 1 x k 1 Move left y k 1 y k select Case end demo script amp plot After loading the script into Scilab the function has to be run from the Console The starting point is always the origin I have run this simulation numerous times and Scilab seems to prefer to go in the northeastern direction break amp continue gt k 0 gt while 1 1 The break command ok k 1 gt disp k m break lets you exit early from a for gt if k gt 6 then end or while end loop or from gt b
109. er o File Filter abe aubdemeist a ok J abe msa i ojo abe home a ea a e E E f tk 2 pvm ISDOS 4 4 ocal cal cal cal oa tlecal ojo ba 3 ee a oT anan 2 E ee ee BSS H il ill l y i GARREK KIF Da i I i pt it a Entering numbers File Edit Preferences Control Applications 2 26X COBA ajase m Scilab allows numbers to be entered in different ways as shown in this example Some expressions have alternate forms For instance there are three power expressions and but Scilab picks them in that calling order Note that e and z are given with Which puts ans limits to the achievable accuracy a function for on a does exist Consult Help if you need to change the display format sgl a From now on I ll show only the contents of the Console l on light yellow background 1415927 Computing precision 1 2 5 50 10 17 Look at the two examples to the left In both cases we are computing 1 5 0 2 but in two different ways In the first case the answer is correct 0 In the second case the answer is 5 55 10 7 which quite obviously is incorrect The reason is that numeric computing has finite precision rounding errors We must take this limitation into account in Scilab simulations Computing precision 2 2 Here are two more cases where finite precision show
110. erested can find a better solution in Steer s Scilab Graphics p 28 Demo 3 1 3 a 3D object script 1 2 Now we ll look at a geometrically more challenging object a 3D plot that moves both in azimuth and elevation Data bounds are not defined separately they are changing with surface mesh resolution The first plot command only defines axes labels rotating_surface sce The 3D surface is first rotated and then tilted after which its position is locked clear clc clf Initialize ea f pixmap on clear_pixmap t pi 20 20 20 Bounds amp mesh resolution First plot command defines labels plot3d1 t t sin t cos t Ynan Yonan x_axis y_axis z_axis Demo 3 2 3 a 3D object script 2 2 The surface rotates around the z axis starting at 45 and finishing at 100 while the tilt angle is constant at 450 for angle1 25 step 100 m When finished rotating the plot3d1 t t sin t cos t angle1 45 surface tilts around the x ge ene axis from 45 up to 80 for angle2 45 step 80 with the rotation angle plot3d1 t t sin t cos t 100 angle2 constant at 100 snow pixmap end f pixmap off With my 1 6 GHz laptop the animation does not run perfectly smoothly the jumps from step to step are noticeable Demo 3 3 3 a 3D object plot The surface has reached its destination rotated to 100 azimuth and tilted to 80 ele
111. erical Maths about what the modules really can do for us ATOMS 3 6 install I decided to try Stephanie Mottelett s Plotting library Click on Install An installation message opens at the bottom and after a go d while Scilab tells that the module has been installed lt a href categories Graphics gt Graphics lt a gt ATOMS Plotting library Main categories salted Version Plotting library 042 1 Author s St phane MOTTELET Description This library is supposed to help you to make plots as if you were using Matlab Version 0 42 includes new macros image imagesc By default all plotlid function names are defined with a leading underscore for example _9cf _gca _plot _suff in order to differentiate these plotlid functions from the original scilab binctions having the same name If you want to use the classical names without sores which will break some native Scitad graphic functions just add the nlotlinmode installation done Piease restart Scilab to take changes into account ATOMS 4 6 new info I also installed the GUI Builder by TAN Chin Luh When Scilab is restarted it informs about the installed K010 1010 S Question What is needed to make use of the installed modules Check with the Help Browser and yes at the very end of the list of contents are new additions Matlab like plotting library and A Graphic User Interfa
112. es Scilab uses the Dot Operator for array operations The table to the right is a list of array operators Arrays building a table Assume that we have a column vector n 0 9 gt n 0 9 We can then build a table gt powers n n 2 2 n with a simple function in pe the shown case with columns for n n 2 and EGG Gi m This type of tables are useful e g when processing measurement data m The second example gt q powers 3 2 powers 4 3 shows that Scilab treats q the created table as a normal matrix gt p powers 4 5 1 2 p a ee a a 32 Element by element multiplication and division m Element by element multiplication with the use of gt A 1 2 3 4 B 56 78 C A B the Dot Operator can also be C performed on two dimensional matrices In the first example we multiply element by element two 2x2 matrices to form a 2x2 product matrix C Note the different result with ordinary matrix multiplication ae 0 2 03633033 a And here we divide the same 0 4285714 0 5 matrices element by element to form a 2x2 matrix of quotients Right and left division As shown in the table above Scilab allows left and right element by element division and respectively The difference between the two is which of the two division elements is the numerator and which the denominator m As shown by the examples left division means that the elemen
113. es HOW TO HYPERLINK IN POWERPOINT 1 Slide Show mode By clicking on the underlined text 2 Norman View mode Put cursor on the underlined text gt right click gt Click Open Hyperlink There is a bug in PowerPoint hyperlinking to certain slides is impossible e g to Chapter 19 Dr EW Johnny Heikell 1 Introduction What is and why use Scilab Q Return to Contents A software package for scientific and engineering computing quite similar to Matlab Scilab is a tool for numeric computing as are Excel GNU Octave Matlab etc The alternative is symbolic computing to which belong Maple MathCad Mathematica and others Developed by Consortium Scilab DIGITEO behind which are a number of French institutions and companies Included in the Scilab package is Xcos a graphic modeling and simulation tool However it is not compatible with Simulink Xcos 1 0 came with Scilab 5 2 before there was Scicos The confusion is complete with a rival called Scicoslab Scilab is free and can be downloaded at www scilab org What Scilab is 2 2 Scilab is matrix oriented just like Matlab It allows matrix manipulations 2D 3D plotting animation etc Itis an open programming environment that allows users to create their own functions and libraries Its editor has a built in though elementary debugger Main components of Scilab are An interpreter Libraries of functions procedures macros
114. ess up gt a 2 b sqt a arrow gt a 2 b sqrt a Correct b 1 4142136 Editing demo Evaluate the function log s 2s cos m 5 1 for s 0 5 0 95 and 1 Do not rewrite the function use instead the up arrow to edit previous commands gt S 5 log s 2 2 s cos pi 5 1 ans 0 8187489 lt gt S 95 Jlog s 2 2 s cos pi 5 1 ans 1 006851 gt S 1 Jlog s 2 2 s cos pi 5 1 ans 0 9624237 Complex numbers a Scilab handles complex numbers as easily as real numbers The variable i stands for V 1 The first example shows how Scilab evaluates some functions with the complex argument x 2 31 m An imaginary sinQ argument produces a result m The second example shows how Scilab does arithmetic operations with two complex equations x and y gt X 2 3 gt abs x ans gt X 2 3 i y 1 1 i azzy 3 6055513 Z1 gt real x 1 44 1 ans 7 4 gt sin Xx ans 9 1544991 4 168907 gt atan imag x real x ans 0 9827937 Vectorized functions Scilab functions are vectorized meaning that functions can be called with vectorial arguments m Inthe shown example first a column vector called t is created Next the vector is used as argument in the sin function in the expression for y a gt y sin 0 2 t If the values of t are of no interest the ps printout can be a
115. f how to create text files with LibreOffice Calc aaa and OpenOffice org Outdoor temp Calc next slide O gt e pe se k 5 Ha oO a o a E o e Reading Spreadsheet data 7 7 Text data in LibO amp OOO lS Save As i lt amea Sn ee lam gt aa gt UDISK 25X E 4 search Save as Text CSV E a _ p select Tab in the Field a awen e delimiter dropdown menu of the window that opens sic That s it pat of tert Mes ee Field options Character set Western Europe Windows 1252 WinLatin aiig Somes 3 Reading Outdoor Indoor Text delimiter i o Hell 4 1 7 320 1 7 Save cell content as shown E Fixed column width The saved csv file looks messy if you open it with Excel but it is ok in Notepad and WordPad mopen m The mopen function is of course more intricate than what one can understand from the discussion above Forgetting binary and text files the general structure of mopen is fd lt err gt mopen file_name lt mode gt where file_name is the entire path of the file including its name mode defines what to do with the data e g m r read an existing file w create a new file amp write into it alt overwrite data in existing file a append open a file and add data to the end fd file descriptor temporary name of the file err error parameter err O if the file is successfully opened err l
116. f parameters using command window Console variables and global variables is not too obvious Global pane in particular can lead to errors that are difficult to etec For the reasons mentioned the use of global variables should be limited to a minimum In conclusion we consider only local variables that are the default setting in Scilab This discussion is therefore trivial Subroutines more formally In the general case where a subroutine has several input arguments in_arg1 in_arg2 and returns several output arguments out_arg1 out_arg2 the structure is function out arel out_arg2 funktion namen argel in_arg2 in_arg3 out_argl expression for lst output argument out_arg2 expression for 2nd output argument endfunction Structure borders are the unction endfunction limiters Input arguments are grouped with brackets parentheses output arguments with square brackets not needed for a single output parameter In both cases the arguments are separated by commas On output arguments The example to the right highlights the basic way in which Scilab manages output arguments of subroutines When you need to influence the management of variables Scilab offers the functions argn 0 varargin and varargout gt function y1 y2 myfunc x1 x2 gt y1 3 x1 gt y2 5 X2 2 gt endfunction gt myfunc 4 7 ans 12 3x4 12
117. fo sci MONPAT a voting Save the script as lotto sci in your preferred file Next Click on the Execute icon of File Edit Search Preferences Window Execute the Editor to mi ae the saved file into Scilab Continues on next slide Ex 1 3 task 1 running If the Console shows a warning check with Help Warning redefining function lotto what it means It can be Use funcprot 0 to avoid this message ignored or the funcprot 0 command can be added to gt exec H Dr EW Writings Scilab examples lotto sci 1 gt exec H Dr EW Writings Scilab examples lotto sci 1 the script to avoid the Warning redefining function lotto warning You can also jump Use funcprot 0 to avoid this message to Chapter 18 for a brief Ts gt help funcprot explanation gt lotto Execute run the loaded function by entering the function name on the Console Se Bs 18 And the winning numbers are Ex 1 3 task 1 discussion This is already an intermediate level programming exercise Don t worry if it gives you problems Most of its details will be repeated later The flowchart of the while end construct is shown to the right Pay attention to the elegant solution for testing uniqueness of the numbers All numbers unique Sort numbers Draw Lotto row length unique numbers lt 7 However in theory it could become an almost infinite loop a We ll retu
118. for a coefficients T tf 5 tf4 AS 5 tf 4 AEA 3 tfA2 20S A272 6 tf c thetaltf theta10 0 0 disp Coefficients for theta1 motion a T c Equations for b coefficients d theta2tf theta20 0 0 disp Coefficients for theta2 motion b T d Equations of motion Lil h L2 3 t linspace 0 2 401 ta 45 gt EATE thetal theta10 a tq theta2 theta20 b tq x1 L1 cos theta1 L2 cos thetal theta2 x2 L1 sin thetal L2 sin theta1l theta2 Plot path of hand plot x1 x2 xlabel x_1 ylabel x_2 title Path of robot hand text 4 3 0 t 0s x_1 x_2 6 5 0 text 0 2 2 t 2s lt _1 2 0 2 Ex 6 5 Robot arm 3 6 Scilab conv The joint motors are controlled by the following polynomial expressions O t O 0 a t a t a t3 a t act b t b lt t Matrix equations are set up and solved for coefficient vectors a b using given initial values 0 and final values O t and the results are used to plot the path of the robot hand robot_motion sce Robot arm motion in two dimensions using a fifth degree polynomial to control the motion See Chapman S J Matlab programming for Engineers 2nd ed for a detailed discussion clear clc clf Initial values angles in degrees Pe eae Finish time Theta 1
119. g when discretizing continuous time models for which Scilab has the function dscrO but which is valid only for state space models See tutorial by Haugen section 9 6 for a brief discussion A detailed discussion is given in the obsolete Signal Processing With Scilab sections 1 5 1 7 and 2 1 you can access both through lt http wiki scilab org 7utorials gt DCP ee functions script This example relates to conv_seconds sce the discussion on strings The script asks for a number of seconds in Chapter 5 checks that the given number is positive then converts the number into hours String as inputQ minutes and seconds argument clear clc time input Give time in seconds The if else end if time lt 0 Check if time gt 0 construct will be disp ERROR negative number Display error message discussed in Chapter 11 Ts and abort execution else minut floor time 60 Convert to minutes Note interplay between seconds modulo time 60 Remaining seconds floorQ and moduloQ hours floor minut 60 Convert to hours i minutes modulo minut 60 Remaining minutes Strings aS disp disp string hours hour s Display answer arguments string minutes minute s string seconds second s end Ex 2 4 string functions execution amp comments Below is the result of three different runs Give time in seconds 0 0 hour s 0 minute s
120. g polygon 1 4 animation_pincon_m2 sce This demo is based on Pingon s Eine Einfuhrung in Scilab The script plots the track of a blue polygon rectangle with red border as it turns around its axis while racing nae counterclockwise in a circular loop on a black background The original contained The rectangle can be chaged to a trapetzoid or other shape rror by changing element values in the matrix polygon Changing Sy obsolete theta arguments in the matrix align gives different effects functions and redundant commands For instance I transformed xsetQ cean cic ci functions to handle II Basic parameters graphics commands as ee bial eps per circular loop explained In Chapter 7 blength 0 6 Basic length of polygon width 0 3 Basic width of polygon radius 0 6 Radius of circular loop revolutions 1 Number of loops to run Ex 6 2 animation of a waltzing polygon 2 4 m The matrix polygon defines length amp width of edges Change them to different values and the rectangle is modified to a different 010 ele a Note the use of the inf constant to fill missing arguments in plot2d0 h gca declares h as a handle The handle is first used to set the background color Basic equations amp definitions t linspace 0 revolutions 2 opi steps x_axis radius cos t x axis of circular loop y_axis radius sin t
121. graphics Q Return to Contents Introduction Animations are a sequence of plots on the Graphics Window executed by showing a plot freezing it while an incremental shift is being calculated and then swapping the old plot for the new one With correct speed and increments it gives the illusion of continuous movement There are two main modes for creating animations Real time mode The animation runs while the script is being executed with the speed being determined by the incremental shifts and computer speed The execution can be influenced slowed down by the realtimeinit and realtime functions Playback mode Possible in Matlab with the getframe and movie commands but Scilab lacks this alternative m A tool for producing animations is the pixmap handle command and the show_pixmap function Example 6 2 however does not use the pixmap command Unless one wants to retain the whole sequence as in Example 6 2 Demo 1 1 4 Introducing pixmap amp xfarcs This demo is adapted from Antonelli amp Chiaverini It exhibits in particular the pixmap and show_pixmap pair of commands m pixmap on oft The pixmap mode is used to achieve a smooth animation With the handle command pixmap on the display is refreshed only when called on by the command show_pixmap Compare this case with the drawlater drawnow pair in ordinary plotting m The script uses the xfarcs fu
122. he second script The script had to be closed to get rid of the gray color I found no way to add ticks amp marks to the box The Axes handle gca showed them as defined but for some reason they are suppressed Help axes_properties gives no explanation m lessons learned Do not exaggerate the extent to which you trade ordinary plot functions plot plot2d0 for handle commands Programming pitfalls don t forget clf Change ttt k lll ul i culls ili i Plots are y all ili superposed f without the ih clf command What to do with xset Examples in Scilab literature and in blog discussions frequently use the function xsetQ It s SO What should we do about it The Help Browser recommends using the graphic objects representation instead setQ getQ handle commands Below are examples of how to substitute xset Note that and gives the blue axes color not the red graph 2 Modified script 1 Initial script with Axes handle with xset command 3 Modified script with set and handle argument xset a practical case Example 6 2 last set of examples is adapted from Pincon The original contained obsolete commands in particular xsetQ I substituted the xsetQ commands with the following handle commands h gca xset backgroung 1 black h background 1 xset color 2 blue fill h foreground 2 xset thickness 3 line thickness h thickness 3 xset
123. hildren then delete graph end Plot planet amp define facet edges a background color grey Box wall color surf rp Xp rp Yp rp Zp Plot planet el gce el foreground color red Facet edge color Plot moon amp define facet edges x_loc Rm sin Az Location on x axis y_loc Rm cos Az Location on y axis C Rm x_loc y_loc 0 Moon center surf C 1 rm Xm C 2 rm Ym C 3 rm Zm Plot moon e2 gce e2 foreground color blue Facet edge color show_pixmap end f pixmap off Ex 6 6 animation with planet amp moon plot And here the beauty is The moon rotates counterclockwise and is shown in its start position As said above this task was not without problems One thing that I failed to do was to tilt the box somewhat differently The handle command a gcal a rotation_angles alpha theta just refused to cooperate and the angles stayed at 51 and 125 respectively a final Ear es ma CP ELE TT eS LETT TAS Measured with tickQ tockQ each moon step takes about 150 milliseconds to perform Dr EW Johnny Heikell 20 Adieu Final words to accompany you in your struggle for survival of the fittest b Q Return to Contents That s it Folks m We have reached the end of our journey The road was longer and bumpier than I anticipated There is much more to Scilab but we are on our way if we master eve
124. ich is number 14 if you count along the columns Next pick out elements of the main diagonal Finally change the elements of the second diagonal to zeros gt M 4 7 10 13 0 0 0 0 M Concatenation 1 2 Concatenation is the process of joining small matrices to make bigger ones gt A 1 2 3 B 4 5 6 C A B In fact even the simplest matrix is formed by concatenating its individual elements The pair of square brackets is the concatenation operator The examples illustrate two basic cases of concatenation the only gt A 1 2 3 B 4 5 6 C A B difference are the transposed matrices C in the second case 4 a nO 3 6 Note that if a semicolon G is placed after a command the result is suppressed but with a comma it is displayed top case Concatenation 2 2 In this example a 4x4 matrix has been created by concatenating four 2x2 matrices gt A 11 12 21 22 gt B 13 14 23 24 m Lines have been overlaid to highlight the fused parts C 31 32041 42 Alternatively we could have gt D 33 34 43 44 concatenated four row or column gt E A B C D vectors a 3x3 matrix plus a row and oo column vector etc E can be treated as a normal 4x4 11 12 matrix For instance the command A 21 22 E 2 3 2 3 picks out the submatrix aa 2 23 41 42 32 33 Operators 1 4 the Colon Operator
125. ile See Help for details Format definitions m Recall the arguments 6 3f n and f in File handling Demo 1 They are part of a set of format definitions d for integers e g 1230 Y f for floating point presentation e g 12 30987 e for exponentials e g 1 2345e 002 s for text string presentation e g Hello World 6 3f to define the output size a the 6 is for the total number of figures a the 3 is for the number of figures after the decimal point n go to a new line t use a horizontal tabulator a Some definition combinations like 6 3f n are possible Format demo script 1 2 This demo aims at clarifying the use of format declarations file_format_demo sce Demonstrates the use of mfprintf format definitions Pay attention that with several variable to be printed I all formats are declared inside a single pair of citation marks before the variables are defined I clear clc Create a new test file for writing fd mopen H Dr EW Writings Scilab examples file_format_demo txt w Some variable to play with HI A 123 45678901 a 0 3 TET b 1 23e 02 Just initial declarations here C at oib The real stuff is on the next slide text Hello World Format demo script 2 2 amp text file No optional text is used in any of the cases You have to be very __ file format demo Notepad E ca
126. imate a planet with a moon rotating around it If possible the bodies should have different colors The task has its first difficulty in finding a way to keep the planet static while the moon rotates My solution is to redraw both bodies for each step that the moon moves Slow but it works The second difficulty is to give the bodies different colors The handle command color_map is nice but it operates on the Figure level and only one color is possible for graphs on the Axes level The presented solution is not perfect since only the edges of the facets that form the spheres have different colors this can be done on the Entity level The third problem is with box alignment It will be discussed on the plot slide Ex 6 6 planet amp moon Beale 1 3 planet_moon1 sce Animation with a moon rotating around a planet The spheres are ccomposed of 3D X Y and Z facets using the surf function to plot The spheres planet clear clc clf moon are built from P rere recta ngu lar facets The Attach defined points to the spheres values of the facets are function x y z facet v h computed here in x cos v cos h Facet x matrix y cos v sin h Facet y matrix z sin v ones h Facet z matrix endfunction subroutine facetQ Basic variables for the planet Jf MAIN Define planet amp moon variables M Planet p 10x10 degree grid vp linspace
127. ime it has spun 21 4 times around its axis and has begun the last 3 4 turn There are 100 position samples on a full loop steps 100 and it completes in a few seconds gt Cli A 74 grayplot amp contour2d This example shows how a gray color scale and contour lines can be combined to create the illusion of a 3D space linspace is multiplied by a 1x3 vector since the color map the third dimension must be a mx3 matrix The color map can be inverted with 1 linspace0 and a nonlinear amplitude function can be added to stress the effects The Sgrayplot function smoothes the plot color compared with the basic grayplotQ function m Contour lines are added grayplot_demo sce Gray area map with level curves using grayplot Sgrayplot amp contour2d to create illusion of a 3D space clear clc clf Color map definitions amp initial declarations f color_map linspace 0 1 64 ones 1 3 20 Plot resolution x linspace 3 3 n 3D plot limits y x Plot function ee Z sin x cos y Sgrayplot x y Z Function to plot Smoothed grayplot Define and add level curves aaa level 8 6 4 2 03 03 2 4 6 8 contour2d x y Z level Ex 6 3 2 2 grayplot amp contour2d cos y The influence of the sine and cosine functions are easy to see note that the origin is in the center of the graph The con
128. indows completion scilab displays a list of all ames that start with somes characters eee or Ctrl A or HOME imove to beginning of current line Ciri B orLEFT BorLEFT moves the cursor one character to the left interrupts Scilab if nothing selected in the onsole else text selected is sentto iclipboard tri D or trl space or AB DELETE deletes the current character Ctrl EorEND moves the cursor to the end of command line tri F or RIGHT moves the cursor one character to the right trl H or z Simple calculations BB Scilab Console Rees pOr Erted Seve Apios 26X pOBA ajast e m The Console can be used as a by writing arithmetic expressions after the command prompt and pressing Enter If no variable name is given Scilab uses the inbuilt variable ans m When a variable name is given here alpha it will be used gt beta 2 2 gamma 3 3 instead 7m is an inbuilt variable arning redefining function beta constant represented by pi a Expressions can be written on the j same line by separating them with ing redefining function gamma a comma the warning can be ignored Scilab displays an executed command unless it ends with a semicolon List of variables The command who Enter produces a list of some Scilab variables At least on my Windows Vista laptop the columns are right aligned French Cele ome are Note that v
129. ing c as input argument denotes continuous The initial state xO 0 0 is not needed since x0 0 is the default value but it is there if we want to make changes Scilab lacks a unit step function the constant input signal is constructed with a unit vector using ones of length t simulation of the defined system was done by the csim function with u t and sys as input arguments csim produces the output arguments y and x which are used by the plotting commands Check Help for a detailed explanation two plots are created since with this particular system x and y would otherwise overlap x and x are plotted automatically the axl gcaQ and axl grid 2 5 pair of commands tells that we want a grid with blue vertical and red horizontal lines Ex 2 3 comments 2 3 For a linear system we can use either a transfer function or state Space representation Their differences Transfer function State space External description Internal description System representation becomes more Representation with more compact with fewer parameters parameters Single input Single output Multiple input Multiple output In common are block diagrams and their manipulations poles and zeros Ex 2 3 comments 3 3 Itis possible to shift between transfer functions and state Space representation tf2ssQ transfer function to state space ss2tfQ state space to transfer function m These functions are needed e
130. ing parameters are yO and tO Note the plot command new way of doing plot2dQ Handle commands come before the legend in this case Scilab gives an error message if you try it the other way Compute using ode which calls previous deff function Initial output voltage amp d v2 dt 0 to 0 Initial time 0 Time 0 0 05 10 Time as abscissa State ode out0 t0 Time RLC State variable vector v2 v2 Plot and add title amp grid Note transposed arguments xtitle Series RLC circuit with step input voltage Time s Input Output voltage v2 t amp d v2 t dt xgrid if plot2d Time State u Time Edit plot Go a qca a children children thickness 2 Make all graphs thicker Add legend must come after handle commands Sop eiceocios ising piv atcatainaniendinba alice cia legend Output voltage v2 t d v2 t dt Input signal 4 Second order ODEs RLC circuit 5 5 plot The plot shows that the circuit is Series RLC circuit with step input voltage Change the l a resistor value to 1 5 Q and it becomes ale S for still higher values of R Handle commands could be used to edit the figure further I did not do it because the main point with this demo is to solve a second order ODE 1 L j Output voltage v2 t d v2 t yvdt Input signal 5 S D o q a h o gt z 3 a s Oo 3 a
131. ion of double integrals using Simpson s rule for calculating double integrals Let s first define a subroutine for Simpson s rule and then add code Axy y eos e x sin y with 0 lt x lt pi pi 2 lt y lt 2 pI for the function the area integral Pe a8 of which should be calculated In this case we l repeat the earlier function 2h L l y cos x x sin y dx dy 2 0 but the script can easily be modified for other algebraic expressions There are numerous variants of Simpson s rule for double integrals for an accurate algorithm see Faires Burden Numerical Methods 3rd ed Brooks Cole 2002 The one given on the next slide is based on Urroz and known as Simpson s 1 9 rule Ex 5 4 Simpson s rule algorithm 1 i1 2 j jt2 where we calculate our function f x y in a rectangular domain R a lt x lt b c lt y lt d Here x is divided into n and y into m even parts so that Cone de k Aye n m Furthermore p ma T fey jad ij fij t Lair pi Alfi ia 3 Leia Lel ee fi Ex 5 4 Simpson s rule script The script is built in four steps 1 Overall headline comments for the program 2 UDF declaration followed by clarifying comments 3 Body of UDF next slide 4 The code for f x y that calls the UDF two slides down double_integration_simpson sce The program calculates the double integral of the function f x y y cos x x sin y b
132. ions optim and fsolv give us tools by which to investigate nonlinear equations and or equation systems optim to find minima and indirectly maxima fsolvQ to find solutions roots to equations equation systems optim is a quite complex function which is evident in the Help Browser s confusing description Here we shall stick to a basic case by applying optim and fsolv to the equation y sinG x SO Sams We solve the problem in two steps First by plotting the graph to get better understanding of the function and simultaneously computing min and max values for y using optim Then we apply fsolve to compute exact root locations with the aid of visual estimates from the plotted graph optim amp fsolve demo 2 4 script optim requires a Scilab subroutine of the type f g ind cost x ind The numeric value of grad is irrelevant Plotting is done with flpot2dQ which is quite similar to plot2dQ I do not know why there has to be a third numeric argument in list Scilab just requires something I tried and cried The second argument of optim istQ 0 defines the gradient that we are interested in optim_list sce Investigation of minima and maxima of the function sinp X 0 1 240 1 A clear clc clf SUBROUTINES eae deff fun1 grad ind cost1 x ind funl sin x x 0 1 2 0 1 grad 0 deff fun2 grad ind cost2 x ind Inver
133. ircumventing a grid 2 color green the problem There were huge problems when I first tried to include the gceQ get current Entity command in the script The background color did not come up after Scilab was reloaded I could not define ticks etc Lessons learned Be sure that you now what you do with gce And a final check on the next slide Ex 3 6 Lissajous figures check After all these modifications let s make sure that we can recall the basic plot by at the end of the script When we run the script Scilab briefly flashes the modified plot deletes it and puts up this window instead The basic Lissajous figures seem to be ok You can use the function pair drawlater and drawnow to avoid the flashing as was done in Ex 3 5 9 Converting Matlab files The embedded Matlab to Scilab translator seems to work and manual conversion is an option k Q Return to Contents Tips on Matlab to Scilab conversion BB Help Browser About halfway down the Help Browser which is not in any logical order y you find Matlab to Scilab Em eee eee runes E Conversion Tips You d eva will see a long list of the aaeaaaiieiesies m2 S ci type of i j porran ae Matlab to Scilab Conversion Tips i e About M2SCI tools fu nctions i Contents Matlad Scilab equivalents i pn Cste Scilab manual gt Matlab to Scilab Conversion Tips 7 ion Equal OA i be
134. is called twice more first with the input argument a then b Interesting way of finding the root location Later we ll do the same using fsolvQ subroutine1 sce Compute amp plot the function y x42 x 1 in the range 5 5 and determine its positive root Assume we know the root lies in the range 1 2 clear clc clf SUBROUTINE para function y para x Subroutine declaration y x42 x 1 Equation parabola endfunction MAIN script x linspace 5 5 100 Range of interest plot x para Call subroutine and plot xgrid Add grid a 1 b 2 Search limits while b a gt 10 4 Accuracy for searching root c at b 2 Midpoint of limits if para a para c gt 0 then IF lower midpoint is positive a C THEN change lower limit else b c ELSE change upper limit end end disp The root lies between Output root limits string a and string b Demo 2 2 plot printout amp comments The root lies between 1 617981 and 1 618042 This demo was borrowed from the pamphlet Scilab pour les Lycees Notice that the calling command was abbreviated to the extent possible Instead of plot x para we could write A Gara plot x a Subroutines have to be declared before the calling main part of the script Later we ll see scripts with multiple subroutines told apart 7 their names Subroutines can also be nested next slide and
135. is is not the case When writing a program for practical applications we must Include the zero check in the script This however requires flow control conditional branching that will be discussed in Chapter 11 Example 2 2 solving currents in a DC circuit Task Determine the four currents i1 i2 i3 and i4 i3 R3 12 for the shown DC circuit Loop 3 As drawn the figure allows aE R2 49 a i1 i2 Kirchhoff s voltage law to be applied However the method leads to a non cece 7 Loop 1 R4 80 Loop 2 square matrix and tools Tee like the Backslash Operator Seta and multiplication with inverse matrices cannot be applied Ex 2 2 mesh currents Instead superposition of E3 4V currents with mesh Raman current equations can be EN used Along the current i3 o loops the diagonal term ieee ee resistances are Rii 109 R22 120 gage eS R4 80 D R33 18 Q ee The common off diagonal resistances are R12 8 Q R13 2 Q R21 8 Q R23 4 Q R31 2 O R32 4 Q You should be able to figure out the logic Ex 2 2 solution These values allow us to write the following mesh current equations circuit1 sce 10 8 2 i 5 Mesh current solution for Example 4 a ee 10 8 2 8 12 4 2 4 18 z ims i 4 u 534 i_n R u PAA residual clean u R i_n We execute the script in the Console and compute manually the current values th
136. ist in Scilab and vice versa Examples are axis compass feather Q fillO narginQ polarQ quadQ quiverQ stemQ stairs and waterfallQ Sometimes alternative Scilab commands exist e g Scilab s plot2d2 0 can compensate for Matlab s stairs sometimes not If not the script may have to be rewritten Scilab s user defined functions must be loaded with getfQ while Matlab has no separate load function Matlab s run data m should be traded for exec data sci in Scilab One more case of manual conversion will be presented in Example 6 5 Chapter 19 Johnny Heikell 10 Subroutines This discussion on subroutines is a prelude to flow control that will be discussed in Chapter 11 B Q Return to Contents Terminology Recall from Chapter 1 that Scilab does not recognize the term subroutine which belongs to the group of varied constructs that Scilab calls function More exact we are talking about user defined functions UDFs an expression that Scilab also does not know Regardless of official Scilab terminology I will when possible use the traditional term subroutine since it is an elegant way of pointing to specific entities in computer programs An introductory demo Recall that introduced the concept of user defined functions UD
137. itled 1 SciNotes earth Preferences Window Execute Commands under Edit are mostly self explanatory Note however the following four Shift Right Left Indent unindent a row by one step this pair should be on the toolbar Comment Uncomment Selection Add delete a comment Editor menu bar 3 5 Preferences gt Untitled 1 SciNotes iF earki Preferences Window Execute The Preferences drop down menu allows you adjust Editor settings to your liking I had difficulties reading scripts on the Editor poor contrast with default settings and used Set Colors and Set Font to change from default values Line numbering Current file encoding Default SciNotes file encoding Line Endings Page Setup Horizontal wrapping Auto completion on Ctrl H Auto completion on if function Ctrl Shift H Enable Auto Reformat Highlight current line Set Colors Set Font Reset default font Configure Tabulation Restore opened files on start up Editor menu bar 4 5 Preferences comment Users can send bug reports to Scilab s development team link at lt www scilab org gt I filed the following report Bug 8802 Default color settings on the Editor produce poor contrast Changing font colors is tedious due to the excessive number of options under Preferences Set colors an overkill you could say I would suggest default settings with just four colors red green blu
138. j Evaluate integral endfunction Ex 5 4 Simpson s rule script amp result Now comes the function f x y that we want to integrate We start by defining integration limits and steps emerges How should one define the calling argument f x y If it is entered as f x y y cos x x sin y i Scilab will complain that x and y i i are not defined The solution is I scilab Message The result of the double integral is 4 9348023 deffO And finally the answer as displayed on the Message box the last digit of the earlier demo was more accurate The exact answer is 12 2 4 934802199 ses Ex 5 4 Simpson s rule discussion I had big problems with this one Scilab repeatedly insisted on coming up with the wrong answer I tried to find the error in several ways Checked manually that the earlier answer 4 9348022 or 1 2 was correct Changed trigonometric functions to exponential equivalents at no avail Checked the algorithm by comparing with solved examples from math and Matlab books m Finally when I plugged in the equation in the now several times changed script the result came out right Most likely I had written sin x instead of cos x Lessons learned It s hard to see bugs in one s own program Another thing The script uses nested loops for i for j 5 end end This should be avoided in Scilab as far as possible because the performa
139. l is defined Note the syslinQ function that defines a linear system Next the responses due to initial state and external input signal u are simulated using csim0 To finish the responses at output y and state variables x and x are plotted in separate windows state_space sce Simulates a continuous time state space system model clear clc A 0 1 1 0 5 B 0 1 C 1 0 D 0 x0 0 0 sys syslin c A B C D x0 t 0 0 1 30 u 0 5 ones 1 length t System matrices Initial state Create cont time c system model Time vector Create constant input signal y x csim u t sys Compute with u input y output x states scf 1 clf Open and clear figure 1 plot t y Plot response in y xtitle RESPONSE AT OUTPUT y t axl gca axl grid 2 5 Handle add grid to y plot scf 2 clf Open and clear figure 2 plot t x Plot response in x xtitle RESPONSE OF STATE VARIABLES t legend x dx dt 1 Add legend to x plot axl gca axl grid 2 5 Handle add grid to x plot Ex 2 3 plots RESPONSE AT OUTPUT y RESPONSE OF STATE VARIABLES Note the use of the function scf number set current figure to produce two plots Ex 2 3 comments 1 3 a Apart from demonstrating matrix operations this example introduced a number of new concepts definition of a linear system with the syslinQ function in which the str
140. lab A full list of built in functions can be found under Help Elementary Functions which also explains requirements on arguments there are both mandatory and optional arguments n E abs sign Absolute value e g abs sinc x sign real f imag f Real amp imaginary parts of a complex f Predefined variables amp constants Main predefined and write protected variables constants are Scilab operators 1 2 The list contains the majority of operators used in Scilab Many will be explained in detail later 7 ind of expression fom ate a conjugate eirin transpose string deimiter C rocon a The pair of left right parenthesis is used for various purposes Addition subtraction Multiplication element by element multiplication Both simple and double quotes are allowed to define character strings Scilab operators 2 2 Right division element by element right division Left division element by element left division Equal to equal or greater than equal or less than greater than less than not equal to two alternatives Computing terminology a brief introduction Arguments Values provided as inputs to a command input arguments or returned by the command output arguments Command A user written statement that provides instructions to the computer statement is an often used alternative Default Action taken or value chosen if none has been provid
141. lem and lethal to the bug Programming pitfalls 2 4 error types Programming errors can broadly be grouped into the following types Logical errors meaning errors in the algorithm used to solve a problem Syntax errors meaning mistakes in the construction of Scilab statements Rounding errors meaning errors due to limited computer accuracy m Logical errors are mostly the result of our limited understanding of the problem at hand and or our limited knowledge of algorithms in general and Scilab in particular m Syntax errors are generally speaking due to human limitations oversight carelessness forgetfulness and the like Typical cases are misspelling mismatched quote marks wrong type of arguments etc m Rounding errors arise from truncations due to hardware limitations digitization of mathematical functions converting between decimal and binary mathematics etc m There is also a fourth type namely errors made by Scilab system designers and programmers They show up as bugs performance limitations poor user interfaces and the like Programming pitfalls 3 4 error messages Incompatible vector lengths Pate eae would be a better error message Inconsistent addition This message is misleading if what you ee intend is but ok if you aim at Inconsistent eE elementwise multiplication E but Wrong multiplication is better still gt 1 2 3 4 5 6 gt sqrt
142. litude value is 100 points but more are needed here clear clc clf f 1 2 pi f Here is the Dot Operator ahi opi again fin 4 pi w t linspace 0 fin 1000 N A 2 exp t m The plot2d produces the 2D 5 A sin w t 10 t 2 phi o oem H atomr ce LULAS LC aS S plot2d t s 5 stands for the x and y axes the number 5 produces a red graph Note fin is used as the end of plot variable name because end is reserved Scilab keyword Ex 1 2 The plot looks as expected including the initial phase shift but it lacks a grid title and axis labels plot2d is a more versatile function than plot which is similar to the plot function in Matlab Ex 1 2 improved plot Here I have added code to plot the grid xgrid0 title xtitleQ and x and y n SINUSOIDAL PLOT labels E xlabelQ ylabelQ Crude but it works 1 5 00 02 04 06 08 10 12 14 16 18 20 Ex 1 2 printing m Scilab s windows Console Editor Graphics Window all have both normal and advanced print functions m One way of getting a coherent printable document is to copy the contents of the windows and paste them into a word processing page Scilab supports m The image shown here was done on MS Word OOo Writer did not recognize Scilab s file type It was then printed as PDF saved as a PNG file and finally cropped with MS Picture Manager That s a tedious method Consult H
143. lve the root correctly Root mark in place Complex numbers demo task Complex numbers have not been discussed at any length before so let s look at a practical problem he task is to solve wt the steady state Go currents i i and i in the shown circuit Recall Example 2 2 and write down the R2 jL R2 impedance matrix Z gt Z R2 R1 R2 by inspection jL RI R Ro Complex numbers demo equations By plugging in numeric values we get the following state space equation I Z u Scilab does not have a function for shifting between polar and rectangular coordinates so we recalculate the voltages manually a rectangular to polar conversion routine is included in the script which is simple in this case il g0 j12 80 J2 1 0 3100 izi 0 100 20 500 40 i3 j12 20 48 0 50 Note that u2 was selected opposite to u1 hence the minus sign Scilab has no problems with doing inverse matrices but as mentioned before left hand division typically gives better accuracy Complex numbers demo script 1 3 The initial step is as Ex 5 the residual check is at the end of the script Now we have to transform rectangular data to polar data The for end loop is run through three times once for each current i1 i3 Computing the magnitude is straightforward circuit3 sce Complex mesh current solution The complex results are convert
144. mments 2 2 m Handle commands are valid only Re eee a b This object has no auto_clear property specific levels Figure Axes Entity at line 4 of function generic_i_h called by etc Help axes_properties gives at line 2 of function n called by e2 auto_clear on at line some hints but mostly you try amp 71 of exec file called by Cry and get error messages ee examplesiplanet_moon1 sce 1 m Scilab has a hidden agenda when it comes to handles For instance the polyline numbering works in quite strange ways Visual edition with handles undoubtedly improves the look of a figure but is the method an overkill The amount of code needed to edit the plot can be larger that used to create the actual plot m We should consider that time money The important thing is to come up with a script that is fit for purpose The rest is luxury It is possible to change Scilab s default settings but information on the subject is hard to come by Kubitzki discusses it briefly Polylines 1 3 xpoly script m This is an to see how well we can work without xpoly sce ordinary plot functions ai Attempt to plot a hexagon with xpoly amp edit m Compare with the xpolyQ with handles Causes erroneous behavior in example given la Help and which Scilab The script must be closed to get rid of the grey background color ra uses the obsolete xset function i clear clc clf m Th
145. n to nn CH is tee 6 podo 4 rthhHt 40 4 not possible here and see how the plot changes 07 7 ajeos gp A 7 T 793 F TET 60 F logarithmic normal l n Note Scilab has a special 37 bode See Example 3 1 w log scale Polar coordinates m Polar coordinates are used frequently in some areas of engineering e g to present antenna lobe diagrams 120 CARDOID Plotting in polar coordinates is done by the command polarplotQ The demo shows the simple script for a cardioid y l1 cos x and its plot Note the markers related to the style 3 argument K ae pe m The plot has been edited eag goot i which is time consuming for i polar plots 240 si Exporting plots Scilab plots can be exported in various picture formats PNG SVG GIF Bitmap etc for use in documents To export Click File Export to in the Graphics Window and select the target file as well as the wished format m An alternative way is to use the xs2 function which for PNG takes the form xs2png window_number file_name The following vectorial and bitmap formats are possible xs2png export to PNG xs2pdfQ export to PDF xs2svg export to SVG xsZeps export to EPS xs2ps export to Postscript xsZemf export to EMF Windows xs2figQ xs2eifO xs2jpgQ xs2bmp xs2ppm export to FIG export to GIF expor
146. n by 1 and compressed multiplied by 0 5 to get the required unit step Ex 4 1 step function rectangular pulse 1 2 The second case is a rectangular pulse with amplitude A as shown in the figure In this case we do it without a user defined function since it leads to a simpler script The plot command can also be simplified somewhat Rectangular pulse ty oe t A to st lt t y t 0 otherwise Ex 4 1 step function rectangular pulse 2 2 Note that the argument u does not have to be defined separately rect can be defined even if style strf and leg are absent Thick figure lines amp graph with increased line thickness l l L l l l l T l l N Ex 4 1 step function comments In the first case unit step the handle command for line thickness is a children children thickness 3 In the second case rectangular pulse Scilab did not accept this form and it had to be rewritten as c a children c cChildren thickness 3 I have no idea why this is the case and Help certainly is of no help In the latter case I happened to write the script without the deffQ function and for a while everything came out all right But when I added handle commands Scilab decided that the variable u is undefined The KISS principle Keep It Simple Stupid did not apply in this case Example 4 2 cones in a 3D space This example is adapted from Chancelier et al pp 163
147. n portal is Wiki Scilab lt http wiki scilab org Tutorials gt were most of the accessible tutorials are listed m Scilab s forge lt http forge scilab org gt is a repository of work in progress many of which exist only in name Its set of draft documents is valuable a Wiki Scilab s HowTo page lt http wiki scilab org howto gt has some articles of interest m Free sites Scilab File Exchange website lt http fileexchange scilab org gt A new discussion forum managed by the Scilab team and dedicated to easily exchange files script data experiences etc Google discussion ja at lt http groups google com group comp soft sys math scilab topics gt MathkB lt http www mathkb com gt Contains among other things a Scilab discussion forum Mostly advanced questions spoken tutorial lt http spoken tutorial org Study_Plans_Scilab gt Screencasts under construction by IIT Bombay Scilab basics Information on the Web 2 2 YouTube has some video clips on Scilab but nothing really valuable Equalis lt http www equalis com gt By registering you gain free access to the discussion forum lt http usingscilab blogspot com gt used to be a very good blog but is now terminally ill Worth checking the material that is still there Scilab India lt http scilab in gt is basically a mirror of Scilab Wiki with added obsolete material and a less active discussi
148. n string gt disp No said mtlb_num2str b m Scilab knows Matlab s conversion command num2str but in the oo a form mtlb_num2str Leave out the square brackets oe a anon ie ted and the elements are displayed as a column starting with the last Last In First Out LIFO Commas are optional with square sear but not with brackets only This is in action Strings 3 6 disp vs L MPATT gt disp in action LIFO This is As seen on the previous slide Thei dispQ gives LIFO output with an ies empty line between the elements in action To avoid the empty line we can use the mprintfQ function with the line declaration n In this case the output is First In First gt Out Note that the argument is a This is single string FIFO in action gt mprintf nThis is nFIFO nin action m Check with the Help Browser for other applications of mprintfQ Strings 4 6 write Input String arguments in the write and input functions allow us to build interactive codes In the shown example write Q is first used to give general information to the user after which input prompts for data required in the calculation m The io 2 argument of the write function tells that the target is the Console All actions after the script is loaded into Scilab take place on the Console strings sce Demo of write and inpu
149. n this material think of an office software package and how little of its potential you really know even if you use it daily The most important next step is to do Scilab simulations on our own to solve problems in our particular sphere of interest Learning hard brainwork a tough rear end m And for everybody s sake keep reminding the Scilab team about the need for a comprehensive up to date tutorial To repeat an old engineering adage The job isn t done until the paperwork is done All the best and take care JH
150. nal insight into working with math on Scilab Q Return to Contents Example 5 1 solving an equation 1 3 This demo is based on M kel m Let s solve the equation ln x x2 7x 10 m We begin by plotting it note how the multiple plot command is constructed The plot reveals that there are two solutions at x 2 and X 5 5 m You can see the roots more exactly by using the Graphics Window s next slide Ex 5 1 solving an equation 2 3 The zoom function gives more precise values for the roots X 1 81 and x 5 49 To improve the accuracy even more we can calculate the roots with the fsolve function next slide Ex 5 1 solving an equation 3 3 fsolve0 delivers the ultimate answer We can also check the error of the result As shown it is close to zero Lessons learned Precise zoom in the Graphics Window produces satisfactory accuracy for most practical engineering purposes two decimals considering that an old engineering adage says that factors that influences the result by less than 10 can be forgotten gt deff y f x y log x x 2 7 x 10 gt X1 fsolve 1 8 f x1 1 8132512 gt x2 fsolve 5 5 f x2 5 4881107 gt f x1 f x2 ans 7 772D 16 ans 4 441 D 16 Exxample 5 2 ODE series RLC circuit 1 5 This example is a modification of the earlier RLC circuit and its second order OD
151. nce is poor in such cases Dr EW Johnny Heikell 15 Working with GUIs The term GUI relates both to Scilab s embedded windows and to user N defined interactive windows lt Q Return to Contents Introduction m Scilab s GUI interface was updated with version 5 Old tutorials e g Campbell et al are therefore of limited value Brief discussions of GUIs can be found in Kubitzki and in Antonelli amp Chiaverini you can read Scilab scripts in German and Italian even if you don t speak the language m Although the GUI interface has improved the Scilab team still cannot be proud of their achievement m GUIs is a large subject the Help Browser identifies about 50 GUI related functions We ll be able to cover only a part of them as always We have earlier seen cases with the dialogue box x_dialog in Ex 1 3 and the messagebox messagebox in Ex 5 4 The first discussion below is about how to tailor Scilab s windows Following that we shall look at some user defined dialog windows A real GUI is presented in Example 6 1 Tailoring windows 1 2 There are four main functions for tailoring either the Console or the Graphics Window Addmenu lt gwin gt button adds new buttons or menus in the main lt optional arguments gt and or Graphics Window command panels deletes buttons or menus created by delmenu addmenu activates buttons or menus created by setmenu addmenu deactivates
152. ncrease title font size a x_label font_style 7 Font Helvetica italic a x_label font_size 2 Increase x label font a y_label font_style 7 Font Helvetica italic a y_label font_size 2 Increase y label font Ex 3 6 Lissajous figures script 2 3 4 Edit ticks amp marks labels ne UE m Gare ale Y axlS ticks amp marks a x_ticks tlist ticks locations labels 1 1 825 55 275 0 275 55 827 1 1 legends ars added e825 557 2750275 OD eo lal Wy m Axes label font color amp size a y_ticks tlist ticks locations labels are redefined 1 1 825 55 275 0 275 55 827 1 1 Pal 625 55 1275 0 7 e270 00 a a Note that Ticks and ee 13 Change label colo a labels_font_color 13 F Legends marks are a labels_font_size 2 Increase label size children to Axes similar to Labels Add amp edit legend hee centaur s A legend is added amp edited legend sin x cos 3x sin 1 5x 0 5 cos 1 5x 4 leg a children 1 Get legend handle leg font_style 2 Font Times leg font_size 2 Increase legend font size leg font_color 1 Font color black leg background 7 Yellow legend box fill Ex 3 6 Lissajous figures script 2 4 4 TO finish the grid is turned on and line colors edited N i Scilab does not have an Bim set gca grid 1 11 equivalent for Matlab s grid on a grid 1 color green this is a way of c
153. nction to fill the moving pie Related Scilab functions are xfarcQ xarcsQ and xarcQ xfarcs is used instead of xfarc because the latter has no provision for defining plot color by arguments and its Axes handle gca does not recognize any children that would allow colors to be defined Demo 1 2 4 movinc pie script Missing x and y values are substituted by onan Only frameflag 3 works n this case Note the imaginary values of thetal amp theta2 Their relative values 27 amp 107 determine the five loops that the pie makes before finishing the full circle xfarcs requires six vector values as its argument The color code is optional the default color is black J animation_ball sce Creates a cut pie that makes 5 loops while moving around a circle Demonstrates the use of the pixmap show_pixmap pair of commands and the use of xfarcs in drawing rs clear clc steps 250 ri 0 5 r2 0 5 f ga f pixmap on for i 1 steps clf Erase pie after each step plot2d Yonan Yonan frameflag 3 Define figure rect 2 2 2 2 axesflag 1 xtitle MOVING PIE thetal i 2 pi steps theta2 i 10 pi steps c cos theta1l r2 cos theta2 sin thetal r2 sin theta2 xfarcs c 1 r1 c 2 r1 2 r1 2 r1 0 360 48 2 f background color grey show_pixmap Display created graphics end f pixmap off of animation
154. nctions under the Edit drop down menu are self explanatory Scilab Console The Cut Copy and Paste fe Edit Pretyrences Control Applications commands have their own icons in 2 Cut qax e the toolbar You also find them by TP Copy Ctrl C right clicking on the PC mouse i pacii Empty clipboard Be careful with Empty clipboard You may not be able to use Copy after clicking it Happened to me Select all Ctrl A I have used Select all a lot to copy paste the demos in this presentation The Console s menu bar 3 6 Preferences The functions under the Preferences drop down menu are quite similar to what you can find on a PC pa Scilab Console File Edit Preferences Fontrol Applications I can only guess that Clear ie ia i ie History is similar to Clear Show Hide Toolbar Private Data in Firefox but i Clear History there is no Show History Clear Console alternative and Help is not helpful Clear Console empties the console You achieve the same by pressing F2 Change visual appearance of the Console The Console s menu bar 4 6 Control I did not need the Control drop down menu a single time while doing this presentation Ee File Edit Preferenc s Control A plications so obviously it is not very useful Resume Abort Interrupt My guess would be that the Resume Abort and Interrupt alternatives give the user a way to interfere with the execution of a p
155. ndling demo 1 2 5 script Create the text txt file with mopenQ fd file descriptor Note the argument w write that is used to create a new file Then fill the file with data in this case created by t using mfprintfQ Note the odd argument 6 3f n that defines the output size explained below file _exercise1 sce The script demonstrates the process of 1 creating a text file on Scilab 2 closing it 3 opening it again to be written into 4 writing the actual data into the file 5 reading certain pieces of data from the file and 6 closing the read file Notice that both close operations are necessary clear clc Create and open a text file for the exercise fd mopen H Dr EW Writings Scilab examples file_exercise1 txt w Create data and write into the exercise file C EG mfprintf fd 6 3f n t Integers from 1 to 18 File handling demo 1 After that the file has to be closed Then opened again to be read r Next we read in its entirety the 1 But the pointer must be returned to the top before we can define which data we want to see Finish by closing the file see below for note on mclose0 3 5 script cont Close exercise file mclose fd Open the exercise file for reading fd mopen H Dr EW Writings Scilab examples file_exercise1 txt r Read and format file con
156. ne I know e Jean Marie Zogqg s Arbeiten mit Scilab und Scicos in German lt http www fh htwchur ch uploads media Arbeiten_mit_Scilab_und_ Scicos_v1_01 pdf gt It s good and informal and contains details that M kel has omitted Needs updating e Wolfgang Kubitzki s mixed tutorials in German that can be found at lt http www mst fh kl de kubitzki gt Quite good a lot of details few practical examples scripts in separate zip files I am indebt to their work Why I did it the way I did it As a grad student at KU in 1990 91 I needed to quickly learn MathCAD or Matlab A fellow student showed me MathCAD basics in 15 minutes with the use of a sine function The lecture went something like this e First you declare the variables that you need e Then you define the function that you want to plot e After that you write the plot commands With that teaching I got started and was able to use MathCAD for my MS thesis Lessons learned Show examples and skip the academic trivia I am deeply grateful to Jim for his lesson We ll repeat it as soon as Scilab is installed and opened Why PowerPoint Why do I release this tutorial as a PowerPoint presentation when there is enough material for a 400 page book There are several reasons 1 2 3 These were originally personal notes I recognized only later that they may be of use to others It is easy to edit PPT material slide by slide You
157. ns in the middle of the screen the picture has been compressed and looks muddled Note however that the GW size is not exactly in proportion to the defined ratio of the screen size and it also changes if we select screensize_px instead of screensize_pt the location changes as well GUI shortcomings m GUIs are not perfected in Scilab The messy text on GUIs in WIKI Scilab org howto tells of very old bugs that remain unsolved Apart from what is mentioned in Demo 2 Cases 5 7 and in the end discussion of Ex 6 1 I have experienced problems with Demo 1 where the listbox may or may not flow over the window frame Ex 6 1 where the labels of the slider and first radiobutton sometimes open with reduced font size a WIKI Scilab org howto also mentions the following limitations Scilab does not allow vertical sliders checkbox radiobutton slider has only smallstep no side arrows and as I found out with Ex 6 1 Scilab gets a lockup when I drag the slider foreground color is always grey pressed radio check always pale red have not tried it only pushbutton radiobutton checkbox and slider support callback The usual recommendation is to use Tcl Tk when advanced GUI solutions are needed another program for you to learn Johnny Heikell 16 File handling We need
158. nstration of black and chart functions clear clc clf s s Gain 2 3 s s 2 1 3 s 2 5 s 2 s 3 system syslin c Gain black system 01 100 chart 8 2 5 3 6 12 5 25 60 120 list 1 1 2 5 x 3 2 plots Amplitude and phase contours of yi 1 y rs Magnitude Db F a gt T D 3 E D gt m E 100 80 Phase deg 1e 002 120 100 80 phase y degree Example 3 3 an RC circuit Let s do a Bode plot using just basic circuit theory and no Laplace rubbish R 1kQ circuit to the right first order u F Usut low pass filter a l The task is to plot both the magnitude gain and phase m The case is the simple RC m The bode function is not a 1 suitable for this case instead CGC we ll used plot2d0 and define M 1 i2nfRC it separately for magnitude and phase Ex 3 3 script m The logspace 1 6 60 command means starting point 10t end point 10 in 60 steps and logarithmic scale Trigonometric phase definition and conversion to degrees m The logflag In argument defines a logarithmic x scale and linear normal y scale Different styles and xgrid arguments have been used to demonstrate their effect bode_RC sce Bode diagram for an RC circuit first order low pass filter clear clc clf R 1e 3 Resistance in ohm C 1le 7 Capacitance in farad freq logspa
159. nteger end disp Accumulated error free sum is string summa Accumulated error free sum is 18 try catch end With no errors the code between try and catch is executed If an error occurs execution immediately shifts to the code between catch and end try foo If an error occurs in i os catch execution continues here mee end m Typically the code between catch and end informs of an expected error e g displ warning cannot access the function 7 Johnny Heikell f 12 Examples Set 4 The first three examples relate to Chapter 10 the rest to Chapter 11 Q Return to Contents Example 4 1 step function unit step 1 2 Step functions are useful in many practical applications As mentioned in Ex 2 3 Scilab lacks a separate function for creating unit steps but we can form them indirectly in Ex 2 3 it was done with a unit vector Here we shall look at two cases where a step is needed In the first demo a step is created with a user defined function that includes the sign function Help is of no help here you don t understand what it says about signQ Unit step y 1 0 to t 0 t lt t y t 1 t gt t Ex 4 1 step function unit step 2 2 Note how the sign function is shifted additio
160. ny times as needed a DE AEEA RYSARE DE KRE 7 You re all set to use Scilab no need to reboot the computer Scilab does not uninstall an old version Linux installation This discussion is valid for Ubuntu gt e merer Ca Md _ etsoftw Software gt Science amp Engineering gt Scilab 10 04 LTS with the GNOME _ 5 ee desktop sonnet m Click Applications Ubuntu omy tae ie ne eee Software Center Science amp igi ini versi b install package scilab cli Engineering and scroll down to mne Scilab then just Click Install 20 450 DAs es ce m Only Scilab 5 3 0 beta 2 is available at the repository For the latest version you must go to Scilab s web site and download Linux binaries The installation however is and I do not l cover it here have not tried it Ubuntu 11 04 with Unity has been released but I have not gone for it The Console Click on Scilab s shortcut icon to open the Console Command Window in Matlab Menu bar Toolbar Command prompt If no shortcut icon has been created Click Start All Programs scilab scilab do not select Scilab Console The Console has other names as well Workspace Startup Main Window etc Bi scia Console erate helene Gontro Appice t 2O B AS B 2 0 Scilab 5 3 2 Consortium Scilab DIGITEO Copyright c 1989 2011 INRIA Copyright c 1989 2007 ENPC Startup execution loading initial environment EN Folks
161. of the four columns i e sum M 34 34 34 34 The transpose statement mM flips the matrix about its main diagonal m The statement diag M oe finally returns the main diagonal as a column vector Sum of rows and columns sum m Scilab returns the sums of rows and ys columns of a matrix A with the a re commands sum A c and sum A r respectively At first sight the use of c and r arguments feels odd The logic is that r returns the sums of matrix columns giving a row vector while c returns the sums of matrix rows a column vector a Alternative statements are 6 sum A r sum A 1 and 15 sum A c sum A 2 24 prod gt A 1 2 3 456 789 A m The product of rows and columns can be formed in a similar way as sums m prod A r returns the product of each column as a row vector m prod A c returns the product slings of each row as a column vector aes m prod A returns the product of 6 all matrix elements Le gt prod A ans 362880 min max Feige a m The same logic continues with the min and max0 functions m min A picks out the smallest 7 element in the matrix and max A the biggest m min A r returns a row vector consisting of the smallest elements in each column m max A c returns a column vector containing the biggest elements in each row
162. on The slider goes from Pa a children children polyline_style 1 Basic style line end to end in 10 steps 7 N ren children polyline_style 3 IF clicked bars The if then else e ae 0 then Check status of color button constructs regi ster the a children children foreground 1 Basic color black status of whichever e E 7 IF clicked blue Ex 6 1 user defined GUI script fie The N ogram first dee an existing GW The size and location of the new GW is defined as a function of the total screen size initial plot that comes in the GW GUI The next thing that we add to the GUI is the EXIT button Note how many arguments the uicontrolQ function has e4 funcprot 0 Here we pick up the Jf MAIN xdel Define window size amp position screen_size get 0 screensize_px Find computer screen size size_x screen_size 3 size_y 7 screen_size 4 7 screensize_px 3rd element 7 screensize_px 4th element h_graph scf 0 Open Graphics Window h_graph figure_size size_x size_y Define GW size h_graph figure_position Position GW in the size_x 5 size_y 6 middle of the screen Open GUI with inital plot initial GUI Add EXIT button Pa h_stop uicontrol h_graph style pushbutton Declare pushbutton string EXIT Pushbutton label fontsi
163. on forum If you know German German technical colleges produce helpful basic tutorials on Scilab better than their French counterparts Search the Internet e g using the terms Scilab Einfuhrung and limit the language option to German Conclusion A lot of resources have gone into producing the existing scattered documentation but they have been uncoordinated and have produced little relative the input effort Lousy management Books There is not a single good textbook in English on Scilab like you find in abundance on Matlab These are the books that I am familiar with e Beater P Regelungstechnik und Simulationstechnik mit Scilab und Modelica Books on Demand GmbH 2010 Basic control systems for mechanical engineers Scilab plays only a minor role in the book e Das V V Programming in Scilab 4 1 New Age International 2008 Reference manual with uninviting layout obsolete functions and no practical examples Useless e Chancelier J P et al Introduction Scilab Deuxi me dition Springer 2007 An intermediate advanced textbook with some engineering applications Approaching obsolescence e Campbell S L et al Modeling and Simulation in Scilab Scicos Springer 2006 Based on Scilab 3 1 over half of the book is on Scicos Of some use but dull the way Springer and LaTeX make them e Gomez C et al Engineering and Scientific Computing with Scilab Birkhauser 1999 Often referred to bu
164. on has not been discussed before but below is a Short Matlab script that draws a pie graph m The pie function also exists in Scilab the difference is that Scilab does not support Matlab s pielabelQ function revenues 31 36 18 8 7 h pie revenues pielabel h Income Tax Sales Tax Borrowing Corporate Taxes Misc A more general sector chart will be presented in Example 6 4 Manual conversion 4 6 Case 3 script amp plot Asa last case let s look at a shifted sinc function In this case the problem is that polardbQ is an informal creation by Matlab users which Scilab does not support X 5 2 pi 1 5 27p i s C a th linspace pi pi length x rho 1 sin x x polardb th rho go 4 p b i gl p 4 4 b lo Similar but not the same as the Matlab plot if radial units are in dB Manual conversion 5 6 Case 3 discussion The polar plot with radial units in dB looks rather counterintuitive since its sidelobes appear to Linear plot be pointing in the wrong direction 120 2 60 Polar plot Manual conversion 6 6 discussion amp hints Manual conversion of Matlab codes to Scilab scripts is possible there are users who claim to do it regularly Scilab for Matlab Users tutorials and Scilab discussion forums can help in understanding the differences m Some Matlab functions simply do not ex
165. os 1 5t nax 1 9 1 9 rect 1 1 1 1 1 11 1 Ex 3 6 Lissajous figures plot 1 The figure defined by sin t cos 3t has full loop its reach is defined e the argument 6 in linspace0 The second figure sin 1 5t 0 5 cos 1 5t is already on its second loop The becomes a if we change the cosine amplitude to 1 Pay attention to the fact that plot2dQ combines sines and cosines arguments element by element That was the basic thing how do we improve it Ex 3 6 Lissajous figures plot 2 This is the plot that has been modified using handles The nee aries anette script is presented on the ho next four slides Major modifications are Both Lissajous figures are arrow style one line is dash dotted Title and axes labels have been added amp edited Background color has been added The legend box has been put in the lower right hand corner text edited and box color z Ao was added amp edited Ok I have done some additions as well Ex 3 6 Lissajous figures Bienes 2 1 4 j handi 2 3 of linspace steps is handles_demo2 3 sce lowered to 40 to better Two Lissajous figures sin t amp cos 3t and show the arrows that are sin 1 5t amp 0 5 cos 1 5t with plot edited used below using handles f m The body of plot2dQ is clear cic clf retained the reminder will i pie z tL fi Ki be done with handles ONA EA A x linspace 0 6 40 40 step
166. ost Scilab tutorials but they window system in Unix should be avoided Why plot and plot2d m Both plot and plot2dQ create 2D plots m plot is borrowed from Matlab Persons with Matlab experience may want to use it and frankly a Scilab has the added plot2d function It offers more options to tailor the plot Multiple plots for instance recall however that multiple plots were done with plot in Ex 1 2 Note plot2d has _also a slight different old syntax plot2d syntax The plot2d Q syntax can be used as a guide for some other plot commands e g for fplot2dQand histplotQ m plot2dQ has the following arguments plot2d logflag x y optional arguments xand y can be either vectors or matrices but with different outcomes for the plot logflag is used only with logarithmic plots we ll se it in a demo later The set of optional arguments is style strf leg rect nax Bece eaa _____ f definitions vector Graph style Minimum bounds for numeric i Legend string the Plot vector xmin Control of display captions often seen ymin xmax ymax by default 081 empty plot2d syntax demo linspace is not accepted here m style 5 produces a red graph leg is empty in sine plot style 9 produces circle marks m A legend is added to the figure with the second plot command Scilab may not accept the legend command as it has done
167. otto row contains 7 numbers 1 39 Task 2 Write a script that calls the previous function or a modification of it if necessary and produces a plot of it to visually indicate if the function produces random numbers Generate 10 000 draws for the task Ex 1 3 task 1 script dt getdate returns dd mm yyyy m rand seed n sets the random gene rator seed to n m dt 9 returns a number between 00 and 59 dt 10 returns milliseconds 000 999 m The while end construct will be covered under the discussion below Function ID not a comment function lotto The function draws 7 Lotto numbers 1 39 by first creating a seed using current date and time second millisecond information dt getdate Pick current date rand seed 1000 dt 9 dt 10 Initialize random generator numbers floor 1 39 rand 1 7 Draw Lotto row while length unique numbers lt 7 If number repeats in row numbers floor 1 39 rand 1 7 then drawn a new row end numbers gsort numbers Sort numbers in decreasing order disp numbers 7 1 1 Display in increasing order endfunction Why the hassle with the seed Without it Scilab generates the same sequence for each session The 1000 t 9 dt 10 argument improves randomness Ex 1 3 task 1 saving This script function differs a bit from the earlier ones so let s go through the save marae operation Wl triangle ares
168. p 5 3 2 gave me problems Intro to problems 3 3 ATOMS and nerds ATOMS is Scilab s system for downloading and installing user developed toolboxes It has given me real gray hair I installed two toolboxes and Scilab plots became a mess Here you can see what the later discussed rotation surface looked like with toolboxes installed I found what caused it after reinstalling Windows and the toolboxes It took me days to get all programs running The idea of user contributions is basically sound but there is a risk with nerds that have more zeal than ability and tenacity to properly test their programs Embedded information Scilab comes with some built in information structures The major ones are The Help Browser that can be accessed from various windows Its utility improved with Scilab 5 3 1 when demonstrations were included but the Help Browser is still a hard nut for newbies It confuses by sometimes referring to obsolete functions Demonstrations that can be accessed from the Console Not really tutorials and some of them act funny some may cause Scilab to crash and others still ask for a C compiler Error messages displayed on the Console Quite basic messages sometimes confusing sometimes too brief a What is really missing is an embedded tutorial or even a user s manual of the Matlab style that is updated with each Scilab release Information on the Web 1 2 The mai
169. pplications z6x oolBIA ajas gt unsetmenu Graphics I gt deamensa i Graphics Interacting with the Graphics Window 1 4 Scilab has numerous commands for interacting with the Graphics Window among these are Waits for a mouse click returns a the number of eae window where the click occurs b position of the as click and c the number of the mouse button used left center right xgetmouse Returns the current position of the mouse RE A F ae handler for the current Graphics seteventhandler Removes the handler The script below is adapted from Help xgetmouse It draws a rectangle on the Graphics Window The rectangle starts off at the location of the mouse pointer at the first click of the left hand button and freezes the rectangle at the second click Interacting with the GW 2 4 script 1 2 Look for a description of data_bounds under Help axes_properties not very helpful According to Help xclick the first vector element should be numeric but Scilab requires a name Look at the arguments of xrectQ it is those that we later play with The third vector element is set to 1 or mouse pointer has moved see Help event handler functions rectangle_selection sce The script demonstrates the use of the mouse related commands xclick xgetmouse and xrect when they are used to draw a rectangle in the Graphics Window clear
170. quadrat end a Scilab function for If else end for end can be nested with if else conditions to allow for execution of alternate statements for variable initial_value step final_value if condition foo else foo end end The next few slides demonstrate a case where random Gaussian pen is generated sorted and reported both verbally and with a plot for If else end demo script 1 3 Only variables nothing to comment for if else sce The script generates Gaussian noise around a fixed signal Each sample signal is sorted according to whether it is within above or below default variance limits 1 The result is reported verbally with strings and is also plotted clear clc clf Define variables of for end loops Signals above upper variance limit Signals below lower variance limit within 0 Signals within variance limits ave 3 Mean average x x axis vector for If else end Random generation as discussed before Note how the signal array is read element by element as j goes from 1 to n demo script 2 3 Generate signal dt getdate Get date rand seed 531 n dt 9 dt 10 Initialize random generator signal ave rand 1i n normal Shifted Gaussian signal Sort signal forj 1 1 n if signal 1 j gt ave 1 then above
171. r Backslash denotes left matrix division Which is important e g in control engineering If A is X A b is equivalent to x inv A b but the computation burden is smaller and the result is more accurate Here you can see the warning given when Scilab sees singularity in left division In this case Matlab produces a different answer than Scilab Example from book by Hunt et al SAS pae 2S7 126 1 boan st gt X A b Warning matrix is close to singular or badly scaled rcond 4 1895D 18 computing least squares solution see Isq 0 0 5641026 0 3846154 Duplicating an mx1 vector to an mxn matrix m The Colon Operator allows us to duplicate vectors to form a matrix gt M 2 2 6 Assume that we have the column ie a vector m 2 2 6 meaning that BE gt A m ones n 1 it has three rows A We want to form a 3x4 matrix where each column consists of the vector m Pay attention to the command m ones n 1 Verbally it can be interpreted as Form a matrix with the number of rows defined by the column vector m and the number of columns defined by the variable n Fill the matrix with ones and multiply each row by the corresponding value of m Repeat just once Singularities and left division The terms singular and nonsingular emerged on the previous slide A requirement of nonsingular square matrices is that the determinant
172. r is too big You guess 17 Number is too small You guess 19 Correct Comments on interactivity The previous demo showed examples of interactive use of strings To instruct the user disp Guess an integer To accept user inputs guess input You guess To the user the inputQ prompt is not very clear since the text string only pops up it should at least blink One must therefore try to find expressive text messages Perhaps the following would be better in the previous case guess input Now Sir Madame type your guess Interactive text strings is a simple form of human machine interfaces Graphical User Interfaces GUIS more are advanced and will be discusses in Chapter 15 there was a case already in Ex 1 3 foo do end The do can be used inside for and while instructions to separate the loop variable definition condition and the instructions The keyword then can be used with if and while The following are examples of for do end and while do then end gt n 9 gt for k 1 1 3 do gt while k lt 3 do if elseif else end The if statement evaluates a logical expression condition and executes a group of statements when the expression is true The optional elseif and else keywords provide for the execution of alternate groups of statements if condition_1 ji joe elseif condition_2 if
173. re within 10 bounds Quite ok for 500 samples GAUSSIAN RANDOM SAMPLES It can be seen that there are one or two samples outside the 30 limit as should be for If else end comments Note how the random data is collected by the signal n array Compare this with the x x k construct that is used later in connection with the discussion on break amp continue This example was a maddening experience I just could not figure out how to make the plot work After hours of attempts I found the problem I had put the random function inside the for end loop What kept me on the wrong track for too long was that the data was collected correctly but is was destroyed when it was brought outside the for end loop However that did not happen if there was a display command inside the loop For instance no semicolon after signal n Speak of coincidences The problem went away when I finally understood to separate data generation from the data sorting loop Lessons learned Be careful with what you put inside loops while end The while end loop repeats a group of statements an indefinite number of times under control of a logical condition The general form of while end is while condition mee loop counter i e coun com le end gt k 1 The code to the right determines from gt while 2 k gt eps which value of k the expression gt k k
174. reading Done comments in the n a e e T Syntax modification Done scri pt a nd ola Macro to tree conversion Copyright c onvyersion o M one of the text 1 L 4 All children will be deleted no HandleVisibility property in Scilab graphics d t 1 L 45 If sinfi is outside 1 1 ocumen S r complex part of output of asin sinfi will be the opposite of Matlab one 1 L 63 Matlab function text not yet converted original calling sequence used Next open the L 64 Matlab function text not yet converted original calling sequence used 1 YETSiIOnN Of treer Done translated script Macro to tree conversion Done Translation may be wrong see the comments in the Editor End of mfile2sci session M to S translator script 1 4 This is the script that the translator delivers It contains comments that may or may not be of importance Statement amp warning added by Scilab Here comes the second warning The Matlab command was clear clo cli if the script is edited with handles In such a case try to create a new script by copy pasting Display mode mode 0 Display warning for floating point exception ieee 1 Monopulse Antenna Pattern clear clc L 4 All children will be deleted no HandleVisibility property in Scilab graphics clf Normalized Aperture Width na 4 Sampling Frequeny Number elements per norm aperture fs 8
175. reak gt end gt end within an if end statement m Execution continues from the line following the end statement gt for j 1 2 m In nested loops break exits only from cr Us me j gt 10r K 1 the innermost loop gt fk gt j 1 amp k lt 8 then i gt continue The continue command send 3 E z k continue is a forced return to the start l aeii of a for end or while end loop gt X not if end loops cn X Statements between continue and the end of the loop will be neglected break demo Give amount of numbers to sum_3 Give next number_13 Give next number_17 Give next number_7 break sce Input m positive integers that are summed OPUI Ee teG SOM nee SUM ISS aan up but the program breaks if the input a is not a positive integer Give amount of numbers to sum_3 clear clc Give next number_17 Give next number_2 n input Give amount of numbers to sum_ Give next number _ 1 summa 0 Reset summa counter fori 1 n wrong negative value number input Give next number_ if number lt 0 Condition number lt 0 Accumulated error free sum is 19 disp wrong negative value break end if number int number Check if integer Give amount of numbers to sum_ 4 disp wrong not an integer Give next number_ 18 break Give next number_ 3 3 end summa summa number Sum up wrong not an i
176. refore black The rectangles move diagonally from corner to corner in 200 steps This demo is adapted from The rectangles move on top animation_rectangles sce Two rectangles slide diagonally over the Graphics Window As they slide over each other their colors are NORed The solution is only partly successful clear clc clf f qcf f pixmap on Double buffer mode f pixel_drawing_mode nor NOR mode f background color lightblue ax gca ax data_bounds 0 4 14 10 Plot limits ax margins 1 1 1 1 Plot framed ax background color lightgrey max_pos 10 Max position of rectangles k nan Auxiliary parameter xfrect k k 4 4 First black rectangle el gce xfrect max_pos k max_pos k 4 4 Second rectangle e2 qce for k linspace 1 10 200 el data 1 2 k e2 data 1 2 max_pos k show_pixmap end Animation loop Show double buffer Demo 2 2 2 frozen plot Here is the animation in progress The NOR function does its job but otherwise something is quite wrong We do not have black rectangles moving across a light grey background The problem is that the command f pixel_drawing_mode nor operates on the whole screen not just on the moving rectangles as intended by Chancelier et al For that reason the XOR operation they use is even worse than NOR I decided to leave the demo in this state Those who are int
177. reful to get it right File Edit Format View Help 123 123 123 123 4568 123 4568 Remember Fa 4 e 0 to close 123 457 3 46 123 complex 0 3000 i0 0123 1 234568e 002 1 23e 002 Hello world I Hello world Hello world Hello world Hello world 4 mfscanf fscanfMat Weused mfscanf in Demo 1 to read scan data from a file Two examples of its use contents mfscanf 1l fd f With this argument it reads the whole contents of the file and formats it four_values mscanf fd f f f f Reads the four first data in the file After reading data the stack pointer remains where it is and we must use the mseek n f command to shift it to a new location The first row in the stack is numbered 0 as indicated by mseek 0 fd in Demo 1 In the discussion of spreadsheet data we used the fscanfMat function to read the data contained in a csv file The function has two alternative call sequences fscanMat filepath lt opt_arg gt to read the numeric part only of scalar matrix data in a text file M text fscanfMat filepath lt opt_arg gt to read the data and include the first non numeric lines The default optional argument is 1g Check with Help for other options Johnny Heikell 17 Animation A brief introduction to creating dynamic
178. reme values e g infinite conditions leading to loop lockup overlooked rounding errors stack overruns etc Work through the program by hand to see if you can spot where things could start going wrong Ask somebody cleverer than yourself for a second opinion Speeding up Scilab 1 4 introduction There are ways to speed up the execution of Scilab programs The three major rules are Replace loops by vectorized operations Particularly with the for loop one should aim at its vectorized alternative Use subroutines whenever possible Avoid time consuming algorithms like Runge Kutta Speed up particularly if we move from loops to vectorized functions requires that we adopt new thinking It s a new learning effort But vectors are after all what Scilab is all about However there is a problem with learning vectorized operations Textbooks tell us to use them but pay little attention to the subject and their few examples are very basic Scilab does not support Matlab s vectorize function Speeding up Scilab 2 4 vector based functions This case is adapted from Baudin The task is to compute the sum of odd integers 1 99 In the first case we use a nested while if end end structure picking odd integers with the modulo function Below is the alternative vectorized solution Clean and simple Advantages Higher level language easier to understand Executes fas
179. rent Figure children Compound A check with gce reveals that in turn has a child This matches the hierarchy that we have seen on the Figure Editor When we call up the Axes handle on the Console it turns out to be really long On the top of the list we find that has a child gt gce ans Handle of type Compound with properties parent Axes children Polyline visible on user_data Handles 6 12 demo step 1 We first define some changes to the window Adjust the window size Add background color Give the window a name Check for details under figure_properties In the Help Browser Handles 7 12 demo step 2 In this step we Move along the hierarchy ladder a gca Edit the plot a background 9 c a children by adding these lines to the Wu pe ala rp script you can bypass the p1 i ee definition stage and write p1 thickness 3 c children foreground etc Note that we move down the hierarchy ladder Figure gt Axes gt Compound gt Polyline Check for details under polyline_properties in the Help Browser Change p1 line_style to pl polyline_style to get a different plot Handles 8 12 demo step 3 et Handle of type Axes with properties As shown earlier the Entity handle parent Figure was quite empty We need to add children Compound labels that can be edited For that ania che visible on we
180. resume abort set of statements Read section 6 7 in ntroduction to Scilab by Micha l Baudin for an explanation My suggestion for painless programming is stepwise development meaning to Develop the script inside out starting with the central equation or similar kernel and executing it using a simple plot or display command Correct the kernel until it works to satisfaction Extend the script stepwise by adding subroutines loops plot commands handle commands etc and test execute after each added step The advantage with stepwise development is that first bugs are isolated to a specific part of the script and easy to identify and second one gets a feeling of satisfaction from each added bug free step Debugging 2 2 validation m Finally even when a script seems to behave correctly we must validate it Don t judge a bird by the colors of his feathers m To validate you can among other things Take a critical look at the solution is it logically sound do you really know what the program does and what it does not do Check for and eliminate redundancies I have found surprisingly many in the textbook examples that I have borrowed Run it for some special cases for which you know the answer If no model cases are available check at least that the answers it provides are plausible and magnitudes are correct Test for unusual events e g where you could end up dividing by zero ext
181. rn to while end loops in Chapter 11 Ex 1 3 task 2 script 1 2 92 The previous UDF must be modified if it is called by a separate code 1 Delete sorting and display and 2 redefine the function ID to allow calling In the latter case it has one or more in that are given to it by the calling command and out by which it returns the result of its calculations to the calling command see next slide lotto2 sce The script asks for the number of Lotto draws that we wish to do using a separate dialog box It then calls the local UDF lottodraw that generates a row of N random Lotto numbers in the range 1 39 It sorts the numbers into a vector by adding one 1 to the relevant vector element for each corresponding hit The result is plotted after the entered number of draws clear clc clf SUBROUTINE function lottodraw The function draws N Lotto numbers 1 39 with N being defined through the input argument in It delivers the drawn row to the calling script command through the output argument out The randomness of the drawn numbers is improved by first creating a seed using current date and time second millisecond information Ex 1 3 task 2 script 2 2 0272 Redefined function subroutine The number of Lotto draws that we are looking for is entered via a separate dialog box x_dialog0 The drawn Lotto numbers
182. rogram a The Help Browser is not very helpful and it does not even recognize the Interrupt command The Console s menu bar 5 6 Applications SciNotes Opens Scilab s Text Editor same as Launch BB scio Console SciNotes in the toolbar D File Edt Prefessnces Control TApplications E S RR SciNotes Xcos Xcos Opens Xcos Matlab to Scilab translator Matlab to Scilab translator Used to translate a Matlab m file to a Scilab sci file Variable Browser j Module manager ATOMS Command History Atoms Opens the online module manager Variable Browser Opens a list with variables same as the Command History Opens a list browsevar command y Up with commands used The Console s menu bar Scilab Help Scilab Demonstrations Web links Scilab Web Site Scilab Online Help Scilab Wiki Scilab ATOMS Web Site File Exchange Mailing lists About Scilab Forge Scilab Help Same as the Bugs And Requests question mark icon in the toolbar Scilab Web l l resources Scilab Demonstrations Shows demos with few comments same command as the cogwheel in the toolbar At least the GUI Uicontrols 2 demo causes Scilab to 6 Help alternatives Introduction Simulation Graphics CACSD GUI Dynamic link Optimization and Simulation Polynomials Signal Processing Tcl Tk Sound file handling Random Spreadsheet Xcos The Console s toolbar Th
183. rograms Q Return to Contents Example 1 1 script fora simple plot Let s elaborate on the example from Scilab in 15 ploti sce minutes We work with the Editor A simple 2D plot of a sine function with the abscissa x 0 10 befor is same E and amplitude A increases with x erore ut with adde TA The function itself is y x comments gt x 0 1 10 The abscissa x is a row vector m Save the function when It A 0 5 x Modulated amplitude row vector has been typed in I call It y A sin 2 x Element by element multiplication ploti sce and have saved it plot y Plot command on my USB thumb drive you can save it wherever you like Torun the script Click on the Editor s Execute icon a What happens is shown on the next slide Note Comments begin with a double Slash Scilab disregards everything behind the when it executes the code Ex 1 1 the Graphics Window As seen before Scilab uses a third window the tO present the plot Information on the executed script is echoed to the Console a re a s0 E co A Tos Ry Sctab tor ee m rarer i miaa Plott sce Tr BS Graphic wand hae Le earn ia displayed on l the Console These three are the windows that we mainly work with but there are more You have already seen a few like the Help Browser and Variable Browser Ex 1 1 using the Console B
184. s exercise showed the essentials of Scilab in engineering applications Scilab s user interface consists of three main windows The Console which pops up when Scilab is opened and on which it outputs textual data numeric answers error messages etc The Editor SciNotes which is the main tool for writing saving and executing scripts programs The Graphics Window on which Scilab presents plots The recipe for using Scilab is the one that Jim taught me First you declare the variables that are needed Then you define the function that you want to plot And finally plug in the plot instruction Speman aa a aaa id 1 That was Scilab Let s go pizza The Console s menu bar 1 6 File Among the functions under the File drop down menu that you will quickly encounter are amp Scilab Console File Ea Preferences Control Applications I Execute From here you can run Scilab scripts or from the geo oS S Editor as seen later SRS ate ee Load environment Ctrl b Open Similar to the Open Save environment Ctrl S command in MS Office i ereneesseeenkdenders programs Display current directory Page setup Change current directory ave arn Display current directo Pay attention to those two they will be needed to tell Scilab where to look for a script that you want to open Quit Ctrl Q The Console s menu bar 2 6 Edit The fu
185. s to allow arrows a The figure handle is called sines sin x sin 1 5 x First figure by gcill after which the cosines cos 3 x 0 5 cos 1 5 x Second figure figure background color plot2d sines cosines rect 1 1 1 1 1 1 1 1 can be defined addition Add background color to Script 1 Get Figure handle f background color grey Grey background color Ex 3 6 Lissajous figures script 2 2 4 m Call Axes handle with gca0 then edit the two Lissajous figures pi amp p2 are Compounds children to Axes m The graphs are Polylines and grandchildren to Axes Title and axes labels must first be added after which they can be edited m Recall that Title is a child to Axes m Check with Help graphics_fonts for details on fonts Edit Lissajous figures Ye ce nee Get Axes handle p1 a children sin 1 5x 0 5 cos 1 5x p1 children 1 polyline_style 4 Arrow mode pi children 1 foreground 2 Change color to blue pi children 1 arrow_size_factor 2 Line thickness p2 a children sin x cos 3Xx p2 children 2 line_style 4 Dash dot line p2 children 2 foreground 5 Change color to red p2 children 2 polyline_style 4 Arrow mode p2 children 2 arrow_size_factor 2 Line thickenss Add amp edit title amp labels AE E aa xtitle Two Lissajous figures x axis y axis a title font_style 8 Font Helvetica bold a title font_size 3 I
186. s up The answers should be 0 zero and T True respectively Note that 1 225D 15 1 225e 16 1 225 10 16 and 1 225 10 16 express the same thing Assume that the mentioned variable a is part of a script with an if then else end structure conditional branching will be covered in Chapter 11 The result is that alternative 1 is never executed because a is never exactly zero We must test a with some finite bounds e g if abs a lt le 6 then heer al lt 10 gt a SiN pi a 1 225D 16 gt 0 1 1 0 0 9 ans F foo if a 0 then alternative 1 else alternative 2 end Displaying graphics The Console can also be used to give commands for Graphic window number 0 plotting graphics Fle Tools Ea 2 3a a 2 The graphical picture is plotted in the that pops up automatically more in Ex 1 m The meaning of the entered code will become clear as we proceed Command line editing S Suppose we make a mistake when entering the command line and Scilab returns an error message Instead of retyping the whole line we can press the up arrow on the keyboard to return the line and correct the mistake In the shown example the function for the square root sqrt was first erroneously typed sqt Note that this is just one of several alternatives for command line editing gt a 2 b sqt a l error 4 Undefined variable sqt Pr
187. se function fun2 sin x x 0 1 2 0 1 grad 0 note minus sign Function MAIN Plot function Plot function xgrid Display min amp max by calling subroutines disp optim list NDcost cost1 0 0 disp optim list NDcost cost2 0 0 END OF MAIN Display y min Display y max fsolve and optim demo 3 4 Her are the minimum and maximum y 2 1199214 values produced by optim And here is the plot It is clear that it has three roots The next task is to locate the roots For that e g 3 0 3 in this case based on which Scilab computes an exact solution for the given neighborhood fsolve and optim demo 4 4 solving the roots As Said on the previous slide approximate values for the roots are x1 3 x2 0 x3 3 With the script is loaded into Scilab we find the solutions on the Console using the command x fsolve x0O f gt X1 fsolve 3 cost1 i ye Equation systems require a different approach See ae e g Zogg pp 66 69 gt X2 fsolve 0 cost1 x2 I said above that the Help 0 Browser is confusing when one tries to find out something about optim A better source is Section 4 2 in Campbell et al gt X3 fsolve 3 cost1 x3 3 1415927 fsolve limitation The script below demonstrates that for values of point close to peak of the sin curve e g 4 6 or 8 Scilab cannot so
188. se is a gca but the alternative a f children also works Pay attention to Compound which has the important children Label and Polyline The latter refers to the actual graph that we plot m Figure can have other children beside Axes These are created by Scilab when we use certain commands Handles 3 12 basic graphics hierarchy _ stucirecrtne Graphics Editor s Object Browser h gcfQ Get figure handle that we have used a gcal Get axes handle or to edit plots a h children X label SEE ae EOE EME EIE y_label y a y_label Get y_label handle z label MAVE san r my AMEN ole Mu ot belel om EDEIS t a title Get title handle compound SREE ENIE leg c children 1 Get legend handle if any polyline EO ERRA e ACEI first graph in plot Handles 4 12 demo starting point As a first exercise let s start from the script that was used in the introduction to handles in Chapter 2 handles_demo1 sce Basic script to demonstrate handles x linspace 0 4 pi 100 plot2d x 0 5 cos x Lessons learned 1 You have to be systematic when working with handles 2 The existing literature is not always correct For instance the method suggested by Steer for changing axes ticks amp marks simply does not work took me hours to figure out Handles 5 12 demo behind the scene gt gca ans Handle of type Axes with properties pa
189. se of the Help Browser s cryptic explanation Basic programming errors Creating infinite loops dividing by zero using instead of etc We all make them there is no way around them than by practicing Ubung macht den Meister On the bright side Scilab works Despite my complaints it mainly does a fine job It is a great thing that it is given away for free to all of us who cannot afford expensive commercial simulation tools Itis a great thing that it is give away for free to all commercial and non commercial institutions that care about cost effectiveness It is a free gift though with restrictions to science and engineering and deserves support of us who happily download whatever comes gratis on the Web m It deserves support because Scilab like other open source IT solutions faces an uphill struggle against vast commercial interests and skeptical individuals Long live the free and open source access community Scilab is released under the French CeCILL license The question is is it really a Free and Open Source license that allows you to release a Scilab copy under a new name the way OpenOffice was turned into LibreOffice Johnny Heikell 2 A first peek at Scilab What you face when trying to get started including Scilab in 15 minutes x
190. ser obec Properes subroutine function for a OEREN sve ode cotrman reusable graphics window Taes EA Figure id A m open Scilab s Graphics o D Window one alternative is by oo the command gcf on the Xai sex 610 Console The empty Graphics Back color Window pops up m On the Graphics Window Click Edit Figure properties to open the Figure editor this va has been explained before al LE E Select a suitable Back color e g 22 for ecclesiastic violet and you can see the frame on the Graphics Window the bar goes only to 32 Global subroutines window demo 2 4 W m you need to play with the Figure Editor for quite a while to fill in all details a the Ticks button on the Graphics Editor It opens a separate window in which you can define amp label grid lines a When all details match you reach something like this a Save it with the help of the Graphics Window Click File Save Edit Axes Ticks Visibility V on Auto ticks I Stepby Object Properties lt lt Subticks 11 7 Locations Labels x Y l Z l Title Style l Aspect Viewpoint l Label Options i mweh y Visibility V on Fill mode Auto position V on Position 0 4855738 0 Auto rotation V on Fontangle o C 90 C 180 C 2707 Foreack colors 1 ee Font size color p 3 Bo J mE DEE Global subroutines window demo 3 4 Scila
191. should aim for vectorized operations if a task requires a lot of loop iterations there is a brief discussion on the subject in Chapter 18 Historical note Konrad Zuse the German who built the first real computer during WW II using over 2000 relays because he did not trust vacuum tubes got everything right except for conditional branches Flow control constructs The following are main constructs that you should be familiar with Branch commands for if else end while if then else end if elseif else end select case elSe end break continue try catch end Logical operators Comparison operators equalto O smaller than greater than smaller or equal to greater or equal to Logical Boolean constants Rumor has it that Scilab will see select case renamed switch case in line with Matlab for end The for end loop repeats a group of statements a predetermined number of times The general expression of for end is for variable initial_value step final_value mele No semicolon end As seen here gt for end_demo sce Compute the square root and square of odd integers from 1 to 8 I 3 1 7320508 9 square cannot ee b d for k 1 2 n 5 2 236068 25 e USE aS root sqrt k variable name quadrat k 2 7 2 6457513 49 since square iS disp k root
192. space la b m creates linearly spaced x and y row vectors from a to b with m equal increments Using vectors x and y the X Y meshgrid x y command creates a 2D matrix in the xy plane Generate Z values for each element of the 2D matrix Plot the resulting 3D function surf _ex1 sce Plot the function Z 2x42 y 2 exp x 2 0 5y 2 for 2 lt x lt 2 3 lt y lt 3 where lt indicates less than or equal to clear clc clf x linspace 2 2 30 y linspace 3 3 30 X Y meshgrid x y Z 2 X 2 Y 2 rexp X 20 5 Y 2 surf X Y Z 3D plots surf plot Ain t that cute The colors may not be all that great but they can be changed with handle commands This will be shown in Example 3 5 surfQ has a called mesh0 that is used in the same way as surf but it lacks shading If you click on the display button for surf in the Help Browser Scilab first displays a number of alternatives and then Contour plots contour m Let s return to the expression z 2 x y exp x 0 5 y2 and plot its 2D contour level height curves It only requires the script s plot command to be changed Vector fields champ The 2D vector field for the expression z 2 x y2 exp x2 0 5 y2 can be visualized by changing the plot expression to champQ and adjusting the intervals in the linspace functions ey yy sF k AAY SAYA
193. start position Theta 1 final position Theta 2 start position Theta 2 final position theta10 19 pi 180 thetaitf 43 pi 180 theta20 44 pi 180 theta2tf 151 pi 180 Equations for a coefficients velocity constraints have been taken into account A E AE ea a E T tf45 tfA4 5 tf 4 4 tf43 3 tfA2 2O AS arte Gtr iy c thetaitf thetal0 0 0 Theta 1 movement Angular velocity Angular acceleration a ihe Coefficient vector a disp Coefficients for thetal motion disp string a Ex 6 5 Robot arm 4 6 Scilab conversion 2 2 By requiring that velocity and acceleration at t 0 be zero the polynomial coefficients a and a become zero This limits the size of the T matrix previous slide to 3x3 The computed coefficient vectors a and b are used to define angular speeds based upon which the hand position is defined in x1 and x2 coordinates Equations for b coefficients d theta2tf theta20 0 0 Theta 2 movement b T d Coefficient vector b disp Coefficients for theta2 motion disp string b Equations of motion Length of upper arm feet Length of lower arm feet Computation steps L2 3 t linspace 0 2 401 tq t 45 t 4 t 43 thetal thetal0 a tq Base motor angular speed theta2 theta20 b tq Elbow motor angular speed x1 L1 cos theta1 L2 cos thetal theta2
194. subplot 224 plot2d4 x sinc x style 2 Plot arrow style xtitle plot2d4 plot2d2 plot2d3 Plot2da demo plot Note You can still see the obsolete plot2d1Q in aarelalerelice plot2d0 should be pease used instead a plot3d10 is not declared dull I ull In contrast obsolete M iji Ill Histograms functions to create them with a Histograms are graphical presentation typically rectangles of one dimensional data m Scilab s main function for plotting histograms is histplot x data opt_arguments Bar diagrams a common form of histograms are given by bar x y width color style or for horizontal bars barh x y width color style a 3 dimensional bar diagrams can be created by the command hist3d z opt_arguments and with added x and y vectors hist3d ist z x y opt_arguments m Check Help for more details Histograms demo script m The script s below are intended to demonstrate different types of histograms presented as 22p subplots histogram_subplot sce Demonstration of histogram types using subplots clear clc clf subplot 221 data rand 1 10000 normal histplot 20 data Traditional histogram subplot 222 y 13 5 6 8 z yj43 22 1 Transpose necessary bar z 0 7 stacked on top of each other subplot 223 hist3d 5 rand 8 4 3D histogram subplot 224 z 10 rand 3 4 x 13 5 6 y 1 2 7
195. t functions clear clc write io 2 This is an interactive demo write io 2 You will be asked to give the base length write io 2 and height of a triangle Scilab then write io 2 computes the area write io 2 Empty row b input Give length of triangle base h input Give height of triangle write io 2 Empty row disp triangle_area string b h 2 This is an interactive demo You will be asked to give the base length and height of a triangle Scilab then computes the area Give length of triangle base 5 Give height of triangle 4 triangle _area 10 Strings 5 6 other useful commands Some of the functions discussed earlier in this chapter can have string matrices below S as arguments prowl nia Not defined for strings max mean Returns the number of rows and columns in S length S Returns the number of characters in each string element Returns the columnwise location of a string element in the find condition ai sort S Returns S with elements rearranged column by column in 8 alphanumerically descending order See demo on the next slide Strings 6 6 demo with ind amp gsort f To the right is a 3x2 matrix called cars The function findO identifies and returns the location of a specified string within the matrix In case there is no match an empty matrix is returned The function sor
196. t 0 integer disp warning must be gt 0 abort Pay attention to the md abort commands if n int n do n should be an integer disp warning not an integer abort end Ex 4 4 script 2 2 Create n random numbers 0 1 or 2 Generation of random dt getdate Get initial seed numbers In the similar rand seed 1000 dt 9 dt 10 Seed random generator manner to Ex 1 3 votes floor 3 rand n 1 Generate votes 0 1 or 2 m Then a select case Transform random numbers to verbal votes oe ee that disp Now this is how you should vote ranstrorms tne for k 1 n random numbers to select T i case en text strings o oe 1 th a Finally the string aes en outputs are grouped case 2 then into threes pay i disp abstain 2 abstain attention to how en handy the modulo if modulo k 3 0 3 votes given function is eae Leave space after 3 rows end endfunction Ex 4 4 comments Scilab has several commands related to forced termination of an ongoing process abort break exit quit return resume Check with Help for details a In this example I had some problems with jumping out of the program in the right manner According to Help Browser the exit command should end the current Scilab session whatever it means It turned out that exit performs more or less like the break command by only ending the present loop quit is a brute that closes down Scilab
197. t gt O if file opening failed merror is a function related to the err argument m It can be a good idea to check the err parameter after a file has been opened has not been done in Demo 1 mclose m A file that has been opened with mopen should be closed with the mclose fd command even if it is automatically closed when Scilab closes However pay attention to the following ambiguous statement in Scilab s Help Browser mclose must be used to close a file opened by mopen If fd is omitted mclose closes the last opened file Be careful with the use of mclose all because when it is used inside a Scilab script file it also closes the script and Scilab will not execute commands written after mclose all mfprintf fprintfMat a The mfprintfQ command is used to convert format and write data in an opened text file The general structure of mfprintf is mfprintf fd lt text a gt format_1 lt text b gt format_2 lt text c gt format_3 value_l value_2 value_3 Which means that each value that we want to print is declared with an optional text the format to be printed in both within a single pair of quotation marks and the value to be printed Format declarations are given on the next slide The format demo two slides down should give a better grasp of what it all means If you ask me it looks really messy m The fprintfMatQ command is used to write a matrix in a f
198. t d where opt d is an optional step size However Scilab s Help Browser recommends using the default value To the right the derivative for the earlier investigated function has been computed at five different points which the diagonal is of interest J derivative outputs a 5x5 matrix in derivative _1 sce Derivative of sin x x 0 1 2 0 1 calculated at selected points clear clc funcprot 0 deff y f x y sin x x 0 1 2 0 1 x 2 1 0 1 2f disp Point Derivative disp x diag derivative f x IPoint Derivative 2 0 2800316 0 6663016 9 0909091 1 2353251 0 3632083 Numeric derivation 2 3 of This script that plots the previous function together with its derivative The equation and its derivative are defined with separate deff functions fplot2dQ accepts the same multiple plot structure aS was used earlier with plot2dQ children 2 and children 3 are used because children 1 is reserved for legend derivative _3 sce Plotting f x sin x 0 1 2 0 1 and its derivative A clear clc clf funcprot 0 x 5 0 01 5 d 0 001 Area of interest Step size Define function amp derivative deff y1 f x y1 sin x x 0 1 42 0 1 x f0 deff y2 g x y2 sin x d x d 0 1 2 0 1 sin x x 0 1 42 0 1 d Plot function amp deriv
199. t file on the Console We can then pick out specific elements from the list 5 5 check gt contents contents 1 2 3 4 5 6 T 8 9 gt five data five data Ne pte gt three_data three_data 6 7 8 gt data_11 data_11 11 Aa 3 gt data_9 11 ans The variables five_data three_data and data_l1l were defined in the script n is the of elements 1 in the vector it belongs to 4 1 We can also address specific elements in the column vector and get the answer as a row vector Spreadsheet data 1 7 Creating data m Scilab does not interface directly B file spreadsheet demo5 ods LibreOffice Calc with spreadsheet o geleigelaaty The File Edit View Insert Format Tools Data Window Help data has to be saved as a text S BaeWsca Bacoa file J Ff AAA EE I started with the new kid on a_i the block The data is the output from an indoor outdoor temperature al Beading _ Outdoor Indoor measurement 2 78 198 3 19 5 The process of saving LibO and 4 198 OOo data as a csv text file is 6 20 0 z 7 20 2 explained later oer 2i 21 1 If you do it in Excel you just f C o oa aa save it as Text Tab H delimited Do not select Unicode Text because Scilab cannot read it Spreadsheet data 2 7 Data saved as csv file And here is the LibO data saved as file_spreadsheet_demobd csv and seen in WordPad the figur
200. t in the left matrix becomes the denominator with right division it is the nominator 5 3 0 6666667 0 75 A A ans gt A B ans The exponent function exp is a special case in being defined as an element by element operation 0 2 0 3333333 1 5 1 38333333 Dot Operator pitfalls In practical simulations Scilab often flashes error messages due to wrong use of the Dot Operator or the absence of it 0 0333333 0 0666667 0 1 0 1333333 A 2a gt B 1 A m A particular problem is division with an integer in the nominator As shown to the here the first case is interpreted by gt E Scilab as B 1 0 A and the second as C 1 0 A Try to remember m Those with experience of Matlab should be aware that the priority of the Dot Operator is different in Scilab This is not an issue with multiplication A few more functions Then command modulo n m computes the reminder of n divided by m where n and m are integers With matrices modulo0 computes the reminder element by element modulo comes handy e g when we need to check if a number is even or odd the if then else end construct will be discussed in Chapter 11 There is a related function pmodulo Check with Help 1 5 modulo gt modulo 3 2 gt n 1 2 10 15 m 2 2 3 5 ans gt modulo n m 1 ans ils 1 0 0 x input Give a number if modulo x 2 0
201. t outdated and of no use On updates amp literature Scilab evolves rapidly and one frequently encounters obsolete features Functions are often declared obsolete although Scilab still may support them and other functions are removed altogether There is obviously no collection of obsolete removed functions and their current equivalents if any The Scilab team is slow with information on major updates For instance the GUI interface is said to have been completely renewed with version 5 x but so far the only poor GUI description that I have seen is for version 4 x It s almost three years now Rapid development is a reason to why the limited literature on Scilab is mostly obsolete sometimes outright misleading I got a hands on experience with all the changes that had to be made to 5 1 1 scripts before they agreed to run on version 5 3 x and not all do Scilab learning obstacles Learning Scilab can be frustrating to a person with limited previous programming experience The biggest hurdles are Lack of hands on tutorials for English speaking newbies The situation is better though not good with some other languages Excessive number of Scilab functions There are some two thousand of them There are often numerous options to select between some of which work some don t some of which you know most you don t Unhelpful Help Browser Even when you have a hunch of which function to use you cannot get it right becau
202. t to JPG export to BMP export to PPM LCU ETA YAE introduction Handles are a thorny subject to Scilab newbies Existing texts give only an incoherent treatment of the topic The user is left with the option try and cry We shall limit this discussion to the most essential handle properties aiming at gaining a basic understanding of how plots are edited with handles It may help to view handles as an alternative to the Figure Editor that we already have used The idea is the same in both The Help Browser discusses the subject under the heading graphics_entites Check also object_editor Recall the introduction to handles in Chapter 2 Handles were already used in Example 2 3 and when discussing polylines This discussion is based on Kubitzki Grafik Eigenschaften verwalten in Scilab section 2 4 3 in Champbell et al and Steer Scilab Graphics 2007 LCU EJA YAE introduction The Graphics Window is built as a hierarchy of objects See the hierarchic tree presented on the next slide which also gives typical commands for each entity m The topmost object in the window is called Figure We use the function gcfQ get current figure to influence the window as it pops up on the screen This is done with the handle f gcf Figure has a child called Axes which in turn has several children and these again may have own children Axes is called by the function gca get current axes The handle in ca
203. tQ orders string elements Co uror aag column in alphanumerical descending order note that the number 343 is accepted without being declared string gt Cars Audi BMW Fiat 343 Saab Xantia cars lAudi BMW Fiat 1343 Saab Xantia gt find cars Saab ans 4 gt find cars Volvo ans gt gsort cars ans Xantia Fiat Audi Saab BMW 343 Symbolic computing m Matrices of character strings are gt sc X y s Z V w constructed as ordinary matrices e g al using square brackets E Avery important feature of matrices of Iz vaw character strings is the capacity to gt tsc trianfml sc manipulate and create functions ee m Symbolic manipulation of mathematical IZ v W objects can be performed using r ee matrices of character strings ae ee gt X 1 y 2 Z 3 v 5 w 4 In the shown cases the function trianfml performs symbolic Be eS triangularization of the matrix sc and 7 ee the function evstr evaluates the 3 9 expression tsc oe Arrays general The term array refers to any systematic arrangement of objects usually in rows and columns numeric arrays diode arrays antenna arrays etc m Arrays have some important uses e g for building tables a Arithmetic operations on arrays are done element by element meaning that addition and subtraction are the same for arrays and matric
204. tents contents mfscanf 1 fd Yof 1 means entire file contents Return position pointer to file beginning mseek 0 fd Following mfscanf 1 the pointer is at the end Read some data from the file five_data mfscanf fd Yof Yof Yof Yof Vf First five data three_data mfscanf fd Yof Yof Vf Next three data n data_9 data_10 data_11 mfscanf fd Yof f Y f Three specific elements Close the file mclose fd File handling demo 1 4 5 the txt file TONE Removable Disk H gt DrEW Writings Scilab examples E ara Name Date modified Type Wbtic toc1 12 10 2009 16 00 scilab 5 3 1 Applic Wb tic toc 2 12 10 2009 16 09 scilab 5 3 1 Applic Mi time space 2 8 2009 18 37 scilab 5 3 1 Applic Mi triangle_area file_exercisel Notepad CIE l Buicontrol 1 m e W e creation Eile Edit Format View Help WB ector field 12 at __ window_demo scg 000 f voting 000 5 x choices_demo Favorite Links E Documents More Folders 000 000 000 000 000 ib wing eee ji 105 items pee 000 000 000 Scilab has put the text file where it was told 000 to on the H drive Check with Notepad Administratioy id CruzerSync DSc Visio a Efile _exercisel W Seminar material Doyo A wu File handling demo 1 The defined read variable contents brings up the contents of the tex
205. ter with large matrices There was a in Scilab 5 3 1 and it returned an Invalid index error message for the latter script Speeding up Scilab 3 4 execution time tic toc Execution time can be measured with the ticQ and toc pair of functions The top script computes values for sin x and orders the result in a table with two columns shown to the far right for only four points The execution time 17 389 s is for the shown script with Scilab looping over 30 000 times The lower vectorized script performs the same task The execution time is 9 msec about 2000 times faster than with the for end loop measure_time1 sce 0 0 9092974 0 7568025 0 2794155 clear clc x nitate vector y Ditto tic Start stopwatch for t 0 0 0002 2 pi x x t y y sin t end time toc Stop watch disp time Display time 0 014 measure_time2 sce clear clc tic t 0 0 0002 2 pi t sin t disp toc Speeding up Scilab 4 4 two more ideas Replace loop by ones for i a 1 100000 x i 1 disp toc tic x ones 100000 1 disp toc In this case the execution time is reduced by a factor of 34 Not nearly as much as in the earlier cases but still a significant improvement typical in practice Replace nested loops with length find 0 k 0 for i 1 1000000 x rand 1 1 if x lt 0 2 then k k 1 end
206. th of an arc f x between points a and b is given by the definite integral b gt deff y g x y sqrt 1 x 2 8 2 x 2 2 L 1 f x 2 2 dx gt L intg 2 3 o 1 125 Let s compute the length of f x x3 24 2xt from x 2 to x 3 The task requires manual derivation which yields f X x 8 2x gt L intg 3 4 9 L 1 7083333 Numeric integration 3 6 double integral principle the 2D area integral of a function f x y over a region The function int2d computes z i consisting of N triangles i b fy ax dy a m x and y must therefore be defined through triangulation matrices X and Y after which the command is Lerr intZd Oo aie and Scilab returns the integration variable I and an estimation of the error err not mandatory aa ome The triangles are ABC and ACD X b bli Y cd as shown in the picture ba dd Triangle elements are inserted angle elements are in ay 4 5 column wise in the matrices ABC ACD ABC ACD Numeric integration 4 6 double integral demo Let s compute the double integral 2T T m 2 0 By looking at the integration limits of the function we find the triangulation matrices X and Y 0 0 mi2 m2 A nl Ya wa m o 2m 21 f cos x x sin y ax dy gt deff z f x y z y cos x x sin y gt X 0 pi pi 0 pi 0J X _ 0 0 3 1415927 3 1415927 3 1415927 0 gt Y
207. the p This field contains the handle of the parent figure 1s i E children ti m e to g et fa m la r FA vector containing the handles of all graphics objects childr E ofthe axes These graphics objects are of type Compound with the He Ip 7 Rectangle Polyline Segs Arc Grayplot see Compound_prop rectangle_properties Browser H i G rtie rti s polyline_properties Johnny Heikell 8 Examples Set 3 On plotting handles control engineering and user defined functions Q Return to Contents Example 3 1 More control engineering plots Example 2 3 and the log scale demo were typical control engineering tasks Recall also the pages on polynomials in Chapter 3 Here we ll look at examples with Bode and Nyquist plots Nichols chart Black s diagram and an Evans root locus plot The first cases use the second order transfer functions s4 203 T s4 36a 2a Gls T s4 0s IOU Se Jas ee The Evans root locus is plotted for Smee C3 352 mm as 2000s 200s3 2554 55 control_eng sce Plot Bode Nyquist Nichols amp Black s and Evans for defined equations I clear clc clf Definition of systems pel Lose sot EE esos eels ee ss poly 0 s
208. then disp Number is even else disp Number is odd end Give a number 24 Give a number 1443 Number is even Number is odd A few more functions 2 5 getdate We saw getdate in action already in Example 1 3 where it was used to improve randomness m Another use of getdate is to put a date stamp on the printout of a simulation m getdate has numerous alternative arguments In addition to those used in Ex 1 3 there are e g the ones shown to the right Check with Help for details The starting point of the clock of getdate is UTC 00 00 on 1 January 1970 gt xp getdate gt xp 1 xp 2 XP 3 xp 4 xp 5 xp 6 xp 7 ans 2011 ans 3 ans 12 83 1 present year 2 present month 3 present week 4 day of the year 5 weekday Thu 6 day of the month 7 hour of the day A few more functions GIS unique m Recall that uniqueQ was used gt M round 5 rand 5 1 dQ was in Ex 1 3 in the condition i are iM a2 length unique numbers lt 7 a to ascertain that the lotto row contained only unique numbers ee 0 and 3 are absent Here unique is used to identify generated integers in the range 1 5 m Inthe second case unique picks out unique rows in a Unique rows are matrix Change r to c to find unique columns lt lt m Compare unique with findO disp
209. tive x sci is also used but x sce Is the default It is good practice to use scripts also for small tasks Then all projects are saved and commented ready for reuse Execute Untitled 1 SciNotes File Edit Search Preferences Window Execute ba ES S amp o 0g But don t forget to create a properly organized archive for your programs Editor menu bar 1 5 File p New a Working directeries Open file in gt File commands that you are most acai likely to run into ee Recent files gives quick access to pen function source We f Open URL 3 recently edited scripts nE New opens a second tab for a Save as new script to be edited min Open opens a saved script into verwrite the Editor weg Open file in and Save file in in Scilab 5 3 Coce gt Ctrl W i i E ae m Print is an ordinary print Close All But This command Exit c Close closes the file in case Editor menu bar 2 5 Edit Cut Copy Paste Delete Copy as HTML with line number Select All Select current block Shift Right Shift Left Comment Selection Uncomment Selection Correct Indentation Remove trailing spaces Generate comments for help_from_sci Make Selection Uppercase Make Selection Lowercase Capitalize character Ctrl Shift C Ctri A Ctrl B Shift Tab Ctrl D Ctrl Shift D Ctrl Shift W Ctrl Shift G Ctrl Shift J Ctri J Ctrl Shift A gt Unt
210. to it The next one is Save as The Execute or Save amp execute icon is what you normally use to run a script The Undo Redo arrows are quite normal The Paste icon is a bit unusual French Ready to go Console command window Your desktop Editor SciNotes should now look something like the one here AS m E we have seen CXA Sensorman Seite oorreor yraght c 1989 2010 INRIA c 1999 29 both the Editor 2 oo cas oo and the Console Done Ceulamials elk col s gt are needed since Msa i me RL when the pn scripts created on the Editor are executed numeric outputs is returned to the Console One more thing 1 2 docking windows It is possible to Scilab windows i e to form a unified workspace similar to the one in Matlab Here is how to do it File Edit Preferences Control Applications 2 aso e T Tis EOE Dolea alase 7 E Press the left ee GTR ae 2 mouse button E TSh TEC on the ie darkened bar of an active window drag over another window and release The next page shows one case One more thing 2 2 docking windows Scilab Console File Edit Preferences Control Applications 2e oOODASSS TJ pott sce Cor EwanitngstSctn examglesipizti see Sento Bloti sce bd gt exec H Dr EW Wrirings Scilab examples ploti sce 1 gt pl ti staple 20 plot ef a sine function Each with
211. tour lines become white if the color map is inversed Steps begin to show in the gray scale if the color map definition is changed to linspace 0 1 32 where the argument 32 stands for halved color resolution Change the plot function from SgrayplotQ to grayplotQ and you ll see the meaning of the variable n 20 Example 6 4 chart script This script is based on a solution by Pierre Lando and shows a method for creating a sector chart with each sector having defined length radius direction width and color The solution can be seen as a more general case of Scilab s pie function that we met in Chapter 9 The most important function in this case is xfarcsQ which we already met in the first animation demo the arcs vector is of course also important since it governs the whole plot SCCLOF Plots four colored sectors in predifined directions and with preditined widths clear clc clf SUBROUTINE The plot2d function defines the figure Xtarcs adds colored sectors to the plot function create_sectors r angle width col plot2d nan onan 1 031 1 1 1 1 arcs rjr 2 r 2 r angle width 2 64 width 64 xfarcs arcs col Add sectors xtitle COLORED SECTORS endfunction MAIN Define sectors ee ee rad 9 6 1 5 Sector radii angle 0 135 225 270 Sector midpoints width 45 75 60 80 Sector widths colors 2 3 5 7
212. trol h_graph This is mostly a style text Declare button text repetition of the horizontalalignment left string Change graph color commands for the backgroundColor 8 8 8 Gray background first radiobutton but Monteizes lAn the position in the GW nosition 40 size_y 380 140 25 Field size amp location is different END MAIN Ex 6 1 user defined GUI and here It is Graphic window number 0 7 File Tools Edit Click on EXIT and GUI DEM sin i A Q E E ert D 0 Dn ral oe pala Ex 6 1 discussion Icopy pasted the script from Antonelli amp Chiaverini into Scilab s Editor The script had to be cleaned up and some redundancies could be removed m I added the second radiobutton and organized the script in what I thought was a more logical fashion m When I executed the script it opened up as expected but the slider was missing After a frustrating weekend I did the whole thing from the beginning but now in steps The error was that I had moved the if then end construct in function new_GUI_data after the plot2dQ command Lessons learned Do the job stepwise and test as you progress As for the lockup my guess is that Scilab runs into a conflict situation when it should update the handle and the previous update still is in progress Example 6 2 animation of a waltzin
213. ts zeros of polynomials can be a tedious undertaking However Scilab has a handy tool for the task in the form of the roots Q function To the right the polynomials on the previous slide have been determined Note that the seed s s has to be defined here as well gt S S gt X ro0ts 2 s 3 s 2 s 3 gt S S gt Z ro0ts 6 5625 22 s 21 5 S 2 8 sS 3 s 4 Fe 0 5 i5 25 9 Poles and zeros plzr Graphic window number 0 m The plzrQ function Ele Tool sit 2 plots the poles and dda EAL zeros of a polynomial m ThesyslinQ function used here will be discussed later m When pressing Enter after the plzr sys command the Graphics Window opens and displays the plot The Graphics Window will be discussed in Example 1 1 Gadgets 1 2 calendar Among Scilab s built in gadgets Z gt calendar 2013 6 ans is a calendar The command ans 1 calendar Jun 2013 returns the calendar for the ans 2 present month the command ar calendar y m returns the calendar for the year and month in case shown for June 2013 Gadgets 2 2 puzzle Another gadget is a puzzle that can be found under anaes Demonstrations Tcl Tk Puzzle cu Genetic Algorithms Simulated Annealing Graphics Signal Processing CACSD Optimization and Simulation Polynomials Simulation Scicos Metanet loses el mg 15 Puzzle Demonstration x A 15 puzzle appears below as
214. ultiplying the original function which is redefined as 2 sin T by sin PHD and xcos PHD Logarithmic scale ask amp script Plot the Bode diagram for the function __100 s 10 s 90 where s iw and the angular frequency w 0 1 1000 Note double dots 100 s 10 in the G command First dot is a decimal point then comes the Dot Operator Put the logarithmic w axis horizontally and the decibel scale y 20 G wi vertically og_plot sce Plot the Bode diagram for the function I G s 100 s 10 s 90 Use the normal ogarithmic x axis and decibel scale on I the y axis clear clc clf Define log scale for w Define imaginary s w logspace 1 3 100 s i w G 100 s 10 s 90 Define G s y 20 log10 abs G Define dB scale for y plot2d w y 5 logflag In Plot y f w xtitle Bode plot for G s 100 s 10 s 90 w log scale y dB scale xgrid Add grid logspace 1 3 100 from 107 to 103 in 100 logarithmically spaced increments ic scale Logarithm the plot Ge O y 2 oO C o co oe oO j D D D iD EG C O e o wo a q 1 wo oO oO Il an O O p 2 a pe am We have not before mentioned doo tte a 4S rebHe es oe alo wee fad a a br ellis 30 7 7 in plot2d Change I
215. under Axes properties Start datatip manager Stop datatip manager getcolor m When working with graphics Graphic window number 1 you may want to check which Ok Cancel colors are available in Scilab and which their codes or names are Scilab s color palette can be brought up by entering the command getcolor on the Console m By clicking on a color in the palette its number RGB composition and name are displayed at the bottom of the window Scilab 5 3 x sep EE does not display the last two 33 green and 34 grey Plot function demos You get a demo of certain plot functions by entering the function name on the Console Examples grayplotQ errbarQ plot3d0 fplot3d10 Axes Editor 7 Axes Editor m Graphic Editor m Objects Browser r Object Properties X Y Z Title Style Aspect Viewpoint The most useful Sonn Label Sete SS 1 1 e ini Yv editing objects are Visibility V on Fill mode T Axes and Auto position V on Position 4 1 PolylineO Here Auto rotation V on F 3 Fontangle 0 C 90 C 180 C 270 the Axes window is J open Fore Back colors LL There een _ Font style SansSerif v object properties Axis Options a_n that can be played Location n with the one for Coor the x axis is shown Data bounds 1 o1 Scale Lin Log Ticks Reverse D Pilot editing demo st
216. vation While testing various parameters I saw this message on the Console long list It disappeared when I re run the script 18 Miscellaneous A hotchpotch of philosophy and realism that hopefully is of use P a N k ay K 1 k y Q Return to Contents The problem solving process The problem solving process for a computational problem typically goes through the following steps not a textbook definition Define the problem answer the question What s the problem Outline a way of solving the problem block diagram DFD etc Define equations and or algorithms solve the math problem Transform steps 2 amp 3 to a software outline or architecture Do the coding in steps and test each step before proceeding Validate the solution does it do what it should do with all input values especially 0 amp and nothing more than it should do ATAT E O D The boundaries between these steps can be blurred iterations are mostly needed and one or two of the steps may be more important than the others Each step also requires a number of subtasks to be performed But in general it helps to have this approach in mind when attacking a problem Good program structures Keep in mind that a program is characterized by a its structure and b by what it does m Give variables clear and meaningful names use single letters only for x y and z axes loop counters j k and the like Split the
217. voided by putting a 0 semicolon after the expression for t 0 1986693 0 3894183 t 0 5 y sin 0 2 t o 0 8414710 m Vectors will be discussed in connection with matrices in Chapter 5 Long command lines i gt p 1 2 3 4 5 6 7 8 9 10 11 12 z Long command S pSr gt 13 14 15 16 17 18 18 19 21 22 23 24 25 can be divided among two or p more lines 329 One tool for that peli O28 I gt q 1 2 1 3 1 4 1 5 1 6 two or three periods to Se B Oe OSII e112 indicate that the statement q continues ie i gt A 12345 Long matrix expressions can 3678910 be written on separate lines gt 11 1213 14 15 by omitting the semicolon that iia normally ends a row bottom Polynomials m You run into polynomials e g if you gt S 8 n use frequency domain state space r analysis in control engineering m Here s s is the seed that defines E T the polynomial of s An alternative A often used form of the seed Yams gt den poly 5 1 5 2 5 3 5 s definition is s 0 s a The polynomials can be defined Fi See 2 A 4 i OS OS S through their root vectors Lo gt fr num den Scilab translates the roots to their respective polynomials m When we divide the num polynomial 2 3 by the den polynomial Scilab 2s 3S S presents the full polynomial expression 6 5625 22s 21 5s 8S S Roots of polynomials Determining roo
218. w see xrect arguments above The while do end loop runs forever unless a second mouse button click changes the condition mouse 3 1 Should a timeout condition be added to the loop Interacting with the GW 4 4 what it does 1 The Graphics Window with instruction pops up as required by A the show_window command LJ Graphic window number 0 rey T E E E O F z Hab Tuto Bg ScilabOR F gg Chanceler aig Scr 2 Put the cursor somewhere o click and drag and click a second time to freeze What do you do with this feature Beats me GUI demo 1 Introducing figure amp uicontrol m Here figure generates the figure opens EB Graphic window number 1 the Graphics Window uicontrol DELE creates the graphical user interface object in the GW and two of the items on the list are highlighted with setQ The central argument in this case is listbox which defines the list _Posttion 50 300 150 100 Note the scrollbar it pops BET Ieee up when the height is too t h value 1 3 High small 100 for all items GUIs pop up window functions Scilab has several commands for creating pop up windows Note that x_message is obsolete and will not work in Scilab 5 2 and later versions messagebox has to be used instead messagebox Message presentation see Demo 2 Cases 1 2 amp 7 x_choose Alternative select
219. x y z cone reach Z Generation of a 3D object x vertical 1 Z cos reach Extension along x axis y vertical 1 Z sin reach Extension along y axis z vertical 1 Z ones reach Vertical z axis endfunction Ex 4 2 script 2 4 Lateral shifts of objects are handled by the function translation0 Non rotational dilatation of objects is the task of homothety rotationQ creates a matrix for rotating objects around the three axes Those are the four user defined functions SUBROUTINE 2 Lateral shifts function XYZ translation vect xyz XYZ vect ones 1 size xyz 2 xyz Translation vector endfunction SUBROUTINE 3 Non rotational dilation center center of dilation f dilation factor function XYZ homothety center f xyz XYZ translation center diag f translation center xyz endfunction SUBROUTINE 4 Rotation function XYZ rotation angle xyz angle angle 180 pi Angle of rotation around axes c cos angle s sin angle Rx 1 0 0 0 c 1 s 1 0 s 1 c 1 Ry c 2 0 s 2 0 1 0 s 2 0 c 2 Rz c 3 s 3 0 s 3 c 3 0 0 0 1 XYZ Rx Ry Rz xyz endfunction Rotation along x axis Rotation along y axis Rotation along z axis Ex 4 2 script 3 4 a eval3dpQ transforms the smooth surface that cone creates into a composition of quadrangular facets Here we plot the basic cone which has its tip in the origin The exterior and interior of
220. x1 position x2 Li sin thetal L2 sin thetal theta2 x2 position Plot path of hand add labels amp legend epee ee ee xlabel x_1 ylabel x_2 title PATH OF A ROBOT HAND hi legend START t Os x_1 x_2 6 5 0 STOP t 2s x_1 x_2 0 2 3 Ex 6 5 Robot arm 5 6 plot amp display PATH OF A ROBOT HAND START t Os x_1 x_2 6 5 0 STOP t 2s x_1 x_2 0 2 Ex 6 5 Robot arm 6 6 discussion The manual conversion from Matlab scripts to Scilab was simple enough Only the following came up Matlab s comment marks had to be changed to Matlab s built in pi function had to be changed to pi Apostrophes quotation marks had to be rewritten but only because copy pasting gives the wrong type instead of The disp command had to be changed because Scilab does not output the a and b coefficients even if respective lines a T d and b T d end without a semicolon a bug Matlab s text command is not recognized by Scilab cf Chapter 9 It allows legend beginnings to be located at precise points The Help Browser does not give an answer on what to do The Scilab for Matlab users compendium by Beil amp Grimm Strele mentions this particular case but does not offer a solution Conclusion We have to stick to Scilab s ordinary legend commands Example 6 6 animation with planet amp moon intro The task is to an
221. y Object interior dark grey Plot third cone rotated M plot3d matrix XYZR 1 4 1 matrix XYZR 2 4 1 matrix XYZR 3 4 1 e2 gce e2 color_mode 24 e2 hiddencolor 30 Get Current Entity handle Object exterior light grey Object interior dark grey STEP 3 ADJUST THE BOX Adjust Axes properties Get Current Axes Box dimensions Rotation of the box Isometric scaling a data_bounds 3 3 3 3 3 3 a rotation_angles 75 77 a isoview on END OF MAIN Ex 4 2 plot m Original cone with tip at the origin Second cone laterally shifted and enlarged m Third cone laterally shifted and rotated And the shading of them is all See Example 4 3 for an explanation Ex 4 2 comments Chancelier et al have not documented their examples too well which in this case together with errors in their solution caused major problems when I tried to understand the script DO NOT UNDERESTIMATE THE NEED TO DOCUMENT PROGRAMS You may be the one that suffers when your code has to be changed years after it was written The first requirement of documentation is liberal use of comments in the code Among the handle commands are some that have not been discussed before f color_map graycolormap el color_mode el hidden_color a rotation_angles and a isoview on recall however the colormap command that was used
222. y calling the subroutine simpson_double x0 xn n yO ym m f clear clc function integral simpson_double x0 xn n yO ym m f The function calculates the double integral of the function f x y in the region x0 lt x lt xn yO lt y lt ym using Simpson s 1 9 rule The x and y ranges are divided into n and m subintervals respectively where both m and n must be even The function modifies m and n if they are odd Ex 5 4 Simpson s rule SC rl pt E E E aes ei cane PEE E if modulo n 2 lt gt O then Check that n is even a n n 1 if not add one This is the body of the end UDF if modulo m 2 lt gt O0 then Check that m is even m m 1 if not add one end It starts by checking and if necessa ry correcting Define x and y increments and region the input parameters n Dx xn x0 n Define delta x and m Dy ym y0 m Define delta y x x0 Dx xn Region and increments of x Here we again meet the y y0 Dy ym Region and increments of y function fevalQ It returns A Calculate double integral a matrix zG j z feval x y f Matrix z i j f x i y j i Sij 0 Initiate Sij fG yG fon i 2221 Sum Sij along x axis for j 2 2 m Sum Sij along y axis Heart of UDF The double Sij Sij z i 1 j 1 z i 1 j 1 z i 1 j 1 z i 1 j 1 summation that produces e PLO PED aege S before forming the final a answer output argument integral Dx Dy 9 Si
223. ze 14 backgroundColor 1 0 0 Red button RGB foregroundColor 1 1 1 White label RGB position 85 size_y 210 50 50 callback xdel 0 CLOSE GW if button pushed Ex 6 1 user defined GUI Baa se 4 6 Here is the uicontrolQ command that controls the slider enl h_slider uicontrol h_graph cae ie a function style slider Declare slider at we nave not met Min 0 Slider start value before Note that wan d Max 100 Slider end value j value 50 Initial slider value rad s are Surrounded by position 10 size_y 270 180 20 Slider size amp location w callback update_slider GOTO to update_slider 1 rt it foo strcat w string h_slider value 10 and rad s Ji not rad s h_text_slider string foo by quotation marks slidelbl strcat w 5 rad s Define initial label CLE within a string h_text_slider uicontrol h_graph style text Declare text os E horizontalalignment center Position in reserved field This is the initial label string slidelbl Add slider label below the slider fontsize 14 backgroundColor 1 1 1 White background And the uicontrol that position 10 size_y 310 180 20 Field size amp location takes care of label changes Ex 6 1 user defined GUI Mlaka 5 6 Th z fi fi E d nh pe Add radiobutton for graph style

Download Pdf Manuals

image

Related Search

Related Contents

Protection system maintenance and benefits of    INSTRUCTION BOOKLET LIvRET d`INSTRUCTIONS  MOCAP, TRUCKS AND VISUALIZATION TOOL USER`S MANUAL  Acas Age Audit Tool User Guide  Dade® Ci-Trol® Coagulação Nível de Controle 2  Watt Meter and Power Analyzer User`s Manual    Blautherm® DUO Technische Hinweise    

Copyright © All rights reserved.
Failed to retrieve file